PreparedStatement:佔位符、預編譯、傳參、執行、關閉鏈接
關閉兩個鏈接mysql
public class Demo3 { public static void main(String[] args) { PreparedStatement ps=null; Connection conn=null; try { Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","dyl123"); //佔位符代替參數 String sql="insert into t_user (username,pwd) values(?,?)"; //能夠防止sql注入 PreparedStatement ps=conn.prepareStatement(sql); //賦值,參數索引從1開始 ps.setString(1, "我"); ps.setString(2, "123456"); //適合多種類型的傳入參數 ps.setObject(1, "你"); ps.setObject(2, "23456"); ps.execute(); //返回是否有結果集,便是否成功運行 //執行insert/update/delete等語句時使用 System.out.println(ps.executeUpdate()); //ps.executeUpdate(),返回更新和影響了多少條記錄 ps.executeQuery(); //執行select語句時選用,返回ResultSet結果集 } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { try { if(null!=conn) { ps.close(); } } try { if(null!=conn) { conn.close(); } }catch (SQLException e) { e.printStackTrace(); } } } }