不用预处理 Statement
//连接数据库操作
public void connection() throws SQLException{
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("数据库驱动");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
try{
con = DriverManager.getConnection("url","root","adminamdin");
stmt = con.createStatement();
rs = stmt.executeQuery("sql");
while(rs.next()){
int x = rs.getInt("字段");
}
}catch(SQLException e){
e.printStackTrace();
}finally{
rs.close();
stmt.close();
con.close();
}
}
使用预处理 PreparedStatement
public void connectionPreparedStatement() throws ClassNotFoundException, SQLException{
Connection con =null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Class.forName("数据库驱动");
con = DriverManager.getConnection("url","root","adminadmin");
pstmt = con.prepareStatement("查询sql");
pstmt.setString(1, "jdjd");
pstmt.setInt(2, 25);
rs = pstmt.executeQuery();
}
Statement是没有预处理的功能的,等到Statement执行SQL语句时,就会向数据库执行SQL语句。
PreparedStatement是预处理SQL语言,在连接的时候就把SQL语句加载j进来,然后等到PreparedStatement真正执行的时候才真正执行SQL语句。
这两者的区别是:
没有预处理的是,statement真正执行时,写入SQL语句。
有预处理的是,在connection返回PreparedStatement对象的时候就加载SQL语句,那个时候就得写入SQL语句。