首页 > 代码库 > JDBC中的PreparedStatement

JDBC中的PreparedStatement

PreparedStatement类从Statement中继承来。

可以将SQL语句传给数据库做编译处理,即在执行的SQL语句中包含一个或多个IN参数,可以设置IN参数值多次执行SQL语句,不必重新给出SQL语句,提高了执行SQL语句的效率

import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
* Created by I am master on 2016/10/3.
*/
public class preparedstatement {
public static void main(String[] args)throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/job";
Properties info=new Properties();
info.put("user","root");
info.put("password","root");
Connection connection= (Connection)DriverManager.getConnection(url,info);

//IN参数用?表示
String sql="select * from jobs where min_lvl>=? and max_lvl<=?";
PreparedStatement preparedStatement=connection.prepareStatement(sql);
//在执行查询操作之前必须对每个IN参数进行设置
//设置IN参数的语法格式:preparedStatement.setXXX(position,value) position为IN参数在SQL语句中的位置,valu为参数被设置的值
preparedStatement.setInt(1,160);
preparedStatement.setInt(2,300);
ResultSet rs=preparedStatement.executeQuery();

while (rs.next()){
String job_id=rs.getString("job_id");
String job_desc=rs.getString("job_desc");
String min_lvl=rs.getString("min_lvl");
String max_lvl=rs.getString("max_lvl");

System.out.print(job_id);
System.out.print(job_desc);
System.out.print(min_lvl);
System.out.println(max_lvl);
}
}

}

JDBC中的PreparedStatement