1.Statement接口不能接受参数
2.PreparedStatement
接口在运行时接受输入参数
3.CallableStatement
接口也可以接受运行时输入参数,当想要访问数据库存储过程时使用
4.示例一:
package com.rong.web; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException; public class Test2 { /**
* @author 容杰龙
*/
public static void main(String[] args) {
Connection conn = getConnection();
PreparedStatement ps = null;
String sql = "insert into student(name,age) values(?,?)";
if (conn != null) {
try {
// 预处理语句对象 可用占位符?解决sql注入漏洞,占位符位置从1开始
ps = conn.prepareStatement(sql);
ps.setString(1, "rjl");
ps.setInt(2, 18);
// 是否返回结果集,此时是false
boolean flag = ps.execute();
System.out.println(flag);
// 返回执行结果的影响行数,此时返回值为1
int effects = ps.executeUpdate();
System.out.println(effects);
/////////批处理/////////
String sql1 = "insert into student(name,age) values('one',28)";
String sql2 = "insert into student(name,age) values('two',27)";
// PreparedStatement构造方法必须有字符串参数
ps = conn.prepareStatement("");
ps.addBatch(sql1);
ps.addBatch(sql2);
int[] ints = ps.executeBatch();
for (int i : ints) {
System.out.println(i);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
} } }
public static Connection getConnection() {
Connection connection=null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://127.0.0.1:3306/rjl";
String user="root";
String password="123123";
connection = DriverManager.getConnection(url, user, password); } catch (Exception e) {
e.printStackTrace();
}
return connection;
} }
5.示例二:
MySQL存储过程
DELIMITER $$
CREATE PROCEDURE getPrice(INOUT myName VARCHAR(20),OUT age INT(20))
BEGIN
SET myName="rjl";
SET age=22;
END $$
java操作
package com.rong.web; import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException; public class Test3 {
public static void main(String[] args) {
Connection connection = Test2.getConnection();
if (connection != null) {
String sql = "call getPrice(?,?)";
try {
//创建存储过程的语句操作对象
CallableStatement cs = connection.prepareCall(sql);
//IN类型参数直接设置set即可
//第一个参数为INOUT类型,需要设置set参数,并注册参数
cs.setString(1, "kobe");
cs.registerOutParameter(1, java.sql.Types.VARCHAR);
//第二个参数为OUT类型,也需要注册
cs.registerOutParameter(2, java.sql.Types.INTEGER);
boolean flag = cs.execute();
System.out.println(flag);
//获取执行存储过程后的OUT结果
String name = cs.getString(1);
int age = cs.getInt(2);
System.out.println(name + ":" + age);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}