java 使用 mysql 存储过程
1、使用最简单的存储过程
存储过程如下
DELIMITER $
CREATE procedure pro_test2()
BEGIN
SELECT * from point;
END $
java中调用
public void testProcedureGetAll() throws Exception{
Connection conn = JDBCUtil.getConnection();
CallableStatement cstmt = conn.prepareCall("{call pro_test2}");
ResultSet rs = cstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getInt(1)+"--->"+rs.getInt(2));
}
if(null != rs){
rs.close();
}
if(null != cstmt){
cstmt.close();
}
if(null != conn){
conn.close();
}
}
2、调用带参数的存储过程
存储过程如下
DELIMITER $
create procedure pro_test1(in inputId INT)
BEGIN
SELECT * from bookinfor b where b.id > inputId;
END $
java中调用
public void testProcedureGetByInputParam() throws Exception{
Connection conn = JDBCUtil.getConnection();
CallableStatement cstmt = conn.prepareCall("{ call pro_test1(2) }");
ResultSet rs = cstmt.executeQuery();
while(rs.next()){
System.out.println("Id:"+rs.getInt("id")+"; bookName:"+rs.getString("bookName")+"; publish:"+rs.getDate("publish"));
}
if(null != rs){
rs.close();
}
if(null != cstmt){
cstmt.close();
}
if(null != conn){
conn.close();
}
}
JDBCUtil
import java.sql.Connection;
import java.sql.DriverManager;
public class JDBCUtil {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/XXXXX";
private static final String USER = "root";
private static final String PASSWORD = "123456";
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}