JAVA调用MYSQL存储过程
工程视图:
代码清单:
myconn.java
package org.apache.sh_mysql.test;
import java.sql.*;
public class MyConn {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=GBK";
private static final String USER = "root";
private static final String PASSWORD ="root";
static {
try {
Class.forName(DRIVER);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取连接
*
* @return
* @throws Exception
*/
public Connection getConnection() throws Exception {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
/**
* 释放资源
*
* @param rs
* @param statement
* @param conn
*/
public void close(ResultSet rs, CallableStatement stmt, Connection conn) {
try{
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
代码清单:
mytest.java
package org.apache.sh_mysql.test;
import java.sql.*;
public class MyTest {
MyConn c=new MyConn();
public void handleData() {
try {
Connection conn=c.getConnection();
CallableStatement call=conn.prepareCall("{call pro_stu_count(?)}");
call.registerOutParameter(1, Types.INTEGER);
call.execute();
int count=call.getInt(1);
System.out.println(count);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void main(String[] args) {
MyTest t=new MyTest();
t.handleData();
}
}