Note about how to operate database using JDBC.
1 | import java.util.Scanner; |
We need to splice the SQL string.
there is an SQL injection risk
if we input 1' or
for username and =1 or '1' = '1
for the password, we can also login.
The SQL statement will become:
1 | SELECT USER, PASSWORD |
So we don’t use Statement to operate database, we use prepared statement
By using the prepared Statement, the SQL is compiled first, and then put the variables(the value) in it, so it won’t be compiled in another way. The main structure of the SQL is not changed.
Because INSERT
, UPDATE
, DELETE
statements don’t have a return value, so we can make them into a common method.
According to the previous article, we already have a common method that can get connection and close connection.
We modify the closeResource()
function to make it able to close PreparedStatement
.
1 | public class JDBCUtils { |
Now we can use them to do insert, update, delete SQL statement.
connect to Database. use the JDBCUtils.getConnection()
method we wrote before.
pre compile the SQL
We wrote the SQL in this way: SELECT * FROM A WHERE id = ?
. the ?
represents the actually value we want to put for.
Then fill the placeholder using PreparedStatement.setObject(index, value)
, the index
starts with 1.
execute SQL using PreparedStatement.execute()
if is an select statement, it returns true, if it is an insert, delete or update statement, it returns false.
close resource.
1 | public void update(String sql, Object ...args) { |
The difference between the previous method and this is that SELECT
query need to receive a return value to represents the selected rows of data.
get connection
pre compile SQL. In order to write a common select query, the Class used to receive row data must have property name exactly same as the column name or the alias name.
fill placeholder
execute SQL using preparedStatement.executeQuery()
and store in result as type ResultSet
.
correspond row data to specific class type.
use ResultSet.next()
to find the next row of data.
And then we need to find the data properties like how many columns the data has. Use ResultSetMetaData
and this is got from ResultSet.getMetaData()
To get column numbers, use ResultMetaData.getColumnCount()
For each column use ResultSetMetaData.getColumnLabel()
instead of ResultSetMetaData.getColumnName()
close resource.
1 | public <T> List<T> queryForList(Class<T> clazz, String sql, Object... args) { |
See the clouseResource
function has another parameter, so we add another function with the same name but different parameters to close the ResultSet
.
Blob
type data.