PreparedStatement接口扩展了Statement对象的功能可以动态的提供/接受参数
获取PreparedStatement对象:con.prepareStatement(SQL语句);
PreparedStatement优点:
- 动态提供和接受参数
- 防止sql注入
- 多次执行效率高
执行SQL语句的方法:
- boolean execute(sql语句):如果检索到ResultSet对象(结果集)返回true,多于用数据库的建立和表格的创建
- int executUpdate(sql语句):返回表格受影响的实体数,多用于表格的数据的插入、更新、删除
- ResultSet executeQuery:返回结果集,多用于查询操作,查询操作无论有没结果都会返回结果集,
package cn.woniuxueyuan.mysqldemo;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* PrepaerStatement对象演示
* @author Administrator
*
*/
public class PrepareStatementDemo {
public static void PreparedDemo(int id, String name) {
/*连接数据库*/
Connection con = msyqlTest.ConDemo();
PreparedStatement pr = null;
/*SQL语句*/
String select = "UPDATE student SET id = ? WHERE s_name = ?;";
try {
/*获取PreparedStament接口实例*/
pr = con.prepareStatement(select);
/*传入参数值*/
pr.setInt(1, id);
pr.setString(2, name);
/*执行SQL语句*/
pr.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
/*关闭资源*/
pr.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}