In Java, interacting with relational databases is one of the most common tasks. JDBC (Java Database Connectivity) is a standard API of the Java platform, used to connect and operate various relational databases. Among them, PreparedStatement
it is an important interface in JDBC, used to execute precompiled SQL statements. This blog will introduce JDBC in detail PreparedStatement
, including its basic concepts, usage and best practices.
What is PreparedStatement?
PreparedStatement
It is an interface in JDBC used to execute precompiled SQL statements. Unlike ordinary SQL statements Statement
, PreparedStatement
SQL statements have been compiled before execution, so they are more efficient and secure, and can prevent SQL injection attacks. PreparedStatement
It is usually used to execute multiple similar SQL queries or updates. It only needs to be compiled once and executed multiple times.
CreatePreparedStatement
To create an PreparedStatement
object, you first need to obtain an Connection
object, and then use prepareStatement
the method to pass in the SQL statement. Here is an example:
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class PreparedStatementDemo {
public static void main(String[] args) {
// 获取数据库连接
Connection connection = getConnection();
try {
// SQL 查询语句,使用 ? 作为占位符
String sql = "SELECT * FROM users WHERE username = ?";
// 创建 PreparedStatement 对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 获取数据库连接的示例方法
private static Connection getConnection() {
// 实现获取数据库连接的逻辑,这里省略具体代码
return null;
}
}
In the above example, we created an object, which was used as placeholders PreparedStatement
in the SQL query statement . You can later use the method to set specific values for these placeholders.?
setXXX
Setting parameters
PreparedStatement
Allows us to set parameter values for placeholders in SQL statements. There are many setXXX
methods for parameter setting of different data types, such as setInt
, setString
, setDouble
etc. Here is an example of setting parameters:
try {
String sql = "INSERT INTO users (username, age) VALUES (?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置第一个参数为字符串类型
preparedStatement.setString(1, "Alice");
// 设置第二个参数为整数类型
preparedStatement.setInt(2, 30);
// 执行 SQL 语句
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
In the above example, we used setString
the and setInt
methods to set specific parameter values for the two placeholders in the SQL statement.
Execute query
To perform query operations, you can use executeQuery
the method, which returns an ResultSet
object to store the query results. Here is an example:
try {
String sql = "SELECT * FROM users WHERE age > ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置参数
preparedStatement.setInt(1, 25);
// 执行查询
ResultSet resultSet = preparedStatement.executeQuery();
// 处理查询结果
while (resultSet.next()) {
String username = resultSet.getString("username");
int age = resultSet.getInt("age");
System.out.println("Username: " + username + ", Age: " + age);
}
} catch (SQLException e) {
e.printStackTrace();
}
In the above example, we executed a query operation with a placeholder, setInt
set the parameter value of the placeholder through the method, then used executeQuery
the method to execute the query, and finally traversed ResultSet
to obtain the query results.
perform update
To perform update operations (such as insert, update, delete), you can use executeUpdate
the method. Here is an example:
try {
String sql = "UPDATE users SET age = ? WHERE username = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置参数
preparedStatement.setInt(1, 28);
preparedStatement.setString(2, "Alice");
// 执行更新
int rowCount = preparedStatement.executeUpdate();
// 输出更新的行数
System.out.println("Updated " + rowCount + " rows.");
} catch (SQLException e) {
e.printStackTrace();
}
In the above example, we perform an update operation with a placeholder, set the parameter value of the placeholder through the setInt
and methods, and then use the method to perform the update operation and output the number of updated rows.setString
executeUpdate
Execute batch processing
PreparedStatement
Batch processing is also supported, which means executing multiple SQL statements at once. This is useful for situations where similar SQL statements need to be executed frequently and can improve performance. Here is an example of batch processing:
try {
String insertSql = "INSERT INTO users (username, age) VALUES (?, ?)";
String updateSql = "UPDATE users SET age = ? WHERE username = ?";
// 创建 PreparedStatement 对象
PreparedStatement insertStatement = connection.prepareStatement(insertSql);
PreparedStatement updateStatement = connection.prepareStatement(updateSql);
// 设置参数并添加到批处理中
for (int i = 1; i <= 3; i++) {
insertStatement.setString(1, "User" + i);
insertStatement.setInt(2, 25 + i);
insertStatement.addBatch();
updateStatement.setInt(1, 30 + i);
updateStatement.setString(2, "User" + i);
updateStatement.addBatch();
}
// 执行批处理
int[] insertResult = insertStatement.executeBatch();
int[] updateResult = updateStatement.executeBatch();
// 输出批处理结果
System.out.println("Inserted rows: " + Arrays.toString(insertResult));
System.out.println("Updated rows: " + Arrays.toString(updateResult));
} catch (SQLException e) {
e.printStackTrace();
}
In the above example, we created two PreparedStatement
objects and used addBatch
the method to add multiple SQL statements to the batch, and then used executeBatch
the method to execute all the SQL statements in the batch at once.
Close PreparedStatement
After use PreparedStatement
, it should be closed promptly to release resources. close
It can be closed using the method PreparedStatement
. Here is an PreparedStatement
example of closing:
try {
// 创建 PreparedStatement 对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
// 设置参数...
// 执行操作...
// 关闭 PreparedStatement
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
Summarize
PreparedStatement
It is an important interface in JDBC for executing precompiled SQL statements. It has the advantages of efficiency, security and maintainability. In practical applications, using PreparedStatement
can effectively prevent SQL injection attacks and improve the performance of database operations. Through the introduction of this article, you should PreparedStatement
have a clearer understanding of the basic concepts and usage of . When writing database-related Java applications, consider using PreparedStatement
to perform SQL operations.
Author information Author: Fanyi CSDN: https://techfanyi.blog.csdn.net Nuggets: https://juejin.cn/user/4154386571867191 |