PreparedStatement接口 发表于 2019-02-01 | 分类于 JAVASE之JDBC PreparedStatement接口 继承于Statement 但是却拥有更安全更高效率的方法 具体如下12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849/** * 此代码演示了PreparedStatement类 * */public class PreparedStatementDemo { public static void main(String[] args) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT", "root", "wangxv123"); // 此处的 ? 是代表占位符 //为了避免SQL的风险,PreparedStatement中使用占位符来先保证参数 String sql = "INSERT INTO students (sid,NAME,sage) VALUES (?,?,?);"; PreparedStatement pst = conn.prepareStatement(sql); //然后在使用set****等各种方法给参数赋值,因为规定了类型,所以可以避免SQL注入的风险 pst.setInt(1,006); pst.setString(2,"哈哈"); pst.setInt(3,22); //也可以使用 pst.setObject 此方法的好处是不需要知道具体类型 pst.execute(); } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException ex){ ex.printStackTrace(); }finally { //关闭PreparedStatement try{ if(pst!=null) { pst.close(); } }catch (SQLException se) { se.printStackTrace(); } //关闭Connect try { if(conn!=null) { conn.close(); } }catch (SQLException e) { e.printStackTrace(); } } }}