本例以JDBC 和 My SQL DataBase为基础,演示执行SQL时对存储过程的支持,本例采用传入参数的方式。

一,存储过程的创建

以My SQL 的存储过程语句:
1
2
3
4
5
6
7
8
9
CREATE DEFINER=`root`@`localhost` PROCEDURE `insertUserInfo`(IN userId int,
in userName varchar (20),
in createdBy varchar(20))
BEGIN

INSERT INTO USER_INFO (USER_ID, USERNAME, CREATED_BY, CREATED_DATE)
VALUES (userId, userName, createdBy, NOW());

END

二,调用存储过程

连接代码:MySqlJDBSUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package com.devnp.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySqlJDBSUtil {
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8";
private static String userName = "root"; // base on your login user name
private static String password = "!qaz2wsx"; // base on your login user

public static Connection getConnection() {

Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, userName, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

public static void connectionClose(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

执行代码:JDBCCallProcedureIn.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.devnp.jdbc;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCCallProcedureIn {

public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub

callOracleStoredProcINParameter();
}

public static void callOracleStoredProcINParameter() throws SQLException{
Connection dbConnection = null;
CallableStatement callableStatement = null;

String insertStoreProc = "{call insertUserInfo(?,?,?)}";

try {
dbConnection = MySqlJDBSUtil.getConnection();
callableStatement = dbConnection.prepareCall(insertStoreProc);

callableStatement.setInt(1, 9);
callableStatement.setString(2, "devp.com");
callableStatement.setString(3, "system");

// execute insertUserInfo store procedure
callableStatement.executeUpdate();

System.out.println("Record is inserted into USER_INFO table!");

} catch (SQLException e) {

System.out.println(e.getMessage());

} finally {

if (callableStatement != null) {
callableStatement.close();
}

if (dbConnection != null) {
dbConnection.close();
}

}

}
}

三,测试

执行代码的结果:
Record is inserted into USER_INFO table!
查看数据库: