java 如何执行sql语句
执行SQL语句的基本方法
在Java中执行SQL语句通常通过JDBC(Java Database Connectivity)实现。JDBC是Java标准库的一部分,用于连接数据库并执行SQL操作。
使用JDBC连接数据库
加载数据库驱动并建立连接是执行SQL的前提。以MySQL为例:
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/dbname",
"username",
"password"
);
执行查询语句(SELECT)
查询语句需要使用Statement或PreparedStatement对象,并通过ResultSet获取结果:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM table_name");
while (rs.next()) {
String columnValue = rs.getString("column_name");
// 处理结果
}
rs.close();
stmt.close();
执行更新语句(INSERT/UPDATE/DELETE)
对于数据修改操作,使用executeUpdate()方法:
Statement stmt = conn.createStatement();
int rowsAffected = stmt.executeUpdate(
"INSERT INTO table_name VALUES (value1, value2)"
);
stmt.close();
使用预编译语句(PreparedStatement)
预编译语句能防止SQL注入并提高性能:
PreparedStatement pstmt = conn.prepareStatement(
"INSERT INTO table_name (column1) VALUES (?)"
);
pstmt.setString(1, "value");
pstmt.executeUpdate();
pstmt.close();
事务处理
通过Connection对象控制事务:
conn.setAutoCommit(false);
try {
// 执行多个SQL语句
conn.commit();
} catch (SQLException e) {
conn.rollback();
}
资源释放
所有数据库资源使用后必须关闭:
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
使用try-with-resources
Java 7+推荐使用自动资源管理:
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
// 执行操作
}
注意事项
不同数据库需要对应的JDBC驱动jar包。连接字符串和驱动类名因数据库类型而异。执行SQL时应注意处理SQLException异常。







