1.Statement接口不能接受参数
2.PreparedStatement
接口在运行时接受输入参数
3.CallableStatement
接口也可以接受运行时输入参数,当想要访问数据库存储过程时使用
4.示例一:
1 package com.rong.web; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.SQLException; 7 8 public class Test2 { 9 10 /** 11 * @author 容杰龙 12 */ 13 public static void main(String[] args) { 14 Connection conn = getConnection(); 15 PreparedStatement ps = null; 16 String sql = "insert into student(name,age) values(?,?)"; 17 if (conn != null) { 18 try { 19 // 预处理语句对象 可用占位符?解决sql注入漏洞,占位符位置从1开始 20 ps = conn.prepareStatement(sql); 21 ps.setString(1, "rjl"); 22 ps.setInt(2, 18); 23 // 是否返回结果集,此时是false 24 boolean flag = ps.execute(); 25 System.out.println(flag); 26 // 返回执行结果的影响行数,此时返回值为1 27 int effects = ps.executeUpdate(); 28 System.out.println(effects); 29 /////////批处理///////// 30 String sql1 = "insert into student(name,age) values('one',28)"; 31 String sql2 = "insert into student(name,age) values('two',27)"; 32 // PreparedStatement构造方法必须有字符串参数 33 ps = conn.prepareStatement(""); 34 ps.addBatch(sql1); 35 ps.addBatch(sql2); 36 int[] ints = ps.executeBatch(); 37 for (int i : ints) { 38 System.out.println(i); 39 } 40 } catch (SQLException e) { 41 e.printStackTrace(); 42 } finally { 43 // 关闭资源 44 try { 45 if (ps != null) { 46 ps.close(); 47 } 48 } catch (SQLException e) { 49 e.printStackTrace(); 50 } 51 try { 52 if (conn != null) { 53 conn.close(); 54 } 55 } catch (SQLException e) { 56 e.printStackTrace(); 57 } 58 } 59 60 } 61 62 } 63 public static Connection getConnection() { 64 Connection connection=null; 65 try { 66 Class.forName("com.mysql.jdbc.Driver"); 67 String url="jdbc:mysql://127.0.0.1:3306/rjl"; 68 String user="root"; 69 String password="123123"; 70 connection = DriverManager.getConnection(url, user, password); 71 72 } catch (Exception e) { 73 e.printStackTrace(); 74 } 75 return connection; 76 } 77 78 }
5.示例二:
MySQL存储过程
1 DELIMITER $$ 2 CREATE PROCEDURE getPrice(INOUT myName VARCHAR(20),OUT age INT(20)) 3 BEGIN 4 SET myName="rjl"; 5 SET age=22; 6 END $$
java操作
1 package com.rong.web; 2 3 import java.sql.CallableStatement; 4 import java.sql.Connection; 5 import java.sql.SQLException; 6 7 public class Test3 { 8 public static void main(String[] args) { 9 Connection connection = Test2.getConnection(); 10 if (connection != null) { 11 String sql = "call getPrice(?,?)"; 12 try { 13 //创建存储过程的语句操作对象 14 CallableStatement cs = connection.prepareCall(sql); 15 //IN类型参数直接设置set即可 16 //第一个参数为INOUT类型,需要设置set参数,并注册参数 17 cs.setString(1, "kobe"); 18 cs.registerOutParameter(1, java.sql.Types.VARCHAR); 19 //第二个参数为OUT类型,也需要注册 20 cs.registerOutParameter(2, java.sql.Types.INTEGER); 21 boolean flag = cs.execute(); 22 System.out.println(flag); 23 //获取执行存储过程后的OUT结果 24 String name = cs.getString(1); 25 int age = cs.getInt(2); 26 System.out.println(name + ":" + age); 27 } catch (SQLException e) { 28 e.printStackTrace(); 29 } 30 } 31 } 32 }