PreparedStatement概述及使用
PreparedStatement使用步骤
-
第一步
编写带有?占位符的SQL语句 -
第二步
使用Connection的prepareStatement( )方法和包含了?占位符的SQL字符串创建PreparedStatement对象并对SQL语句进行预编译 -
第三步
使用PreparedStatement的setXXX(index , value)方法传入实参取代之前的?占位符 -
第四步
使用PreparedStatement的execute( )、 executeUpdate( ) 、 executeQuery( )方法执行 SQL 语句使用PreparedStatement实现对学生表的增删改查,代码如下:
1.查询学生表里的内容:
public static void main(String[] args) {
select();
}
public static void select(){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//建立连接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test0221", "root", "root");
String sql = "select * from student";
//创建preparedStatement
preparedStatement = connection.prepareStatement(sql);
//执行SQL
resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
Student student = new Student(id, name);
System.out.println(student);
}
}
catch (Exception e){
System.out.println(e);
}
//关闭资源
finally {
if