本例以JDBC 和 My SQL DataBase为基础,演示执行SQL时对存储过程的支持,本例采用传入参数并获取返回值的方式。
一,存储过程的创建
1 2 3 4 5 6 CREATE DEFINER= `root`@`localhost` PROCEDURE `findUserInfoById`(IN userId int )BEGIN select * from USER_INFO where USER_ID = userId ;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" ; private static String password = "!qaz2wsx" ; 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(); } } } }
执行代码:JDBCCallProcedureOut.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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 package com.devnp.jdbc;import java.sql.CallableStatement;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.util.Date;public class JDBCCallProcedureOut { public static void main (String[] args) throws SQLException { callOracleStoredProcOutParameter(); } public static void callOracleStoredProcOutParameter () throws SQLException{ Connection dbConnection = null ; CallableStatement callableStatement = null ; String insertStoreProc = "{call findUserInfoById(?)}" ; try { dbConnection = MySqlJDBSUtil.getConnection(); callableStatement = dbConnection.prepareCall(insertStoreProc); callableStatement.setInt(1 , 9 ); ResultSet rs = callableStatement.executeQuery(); System.out.println("select USER_INFO record!" ); while (rs.next()) { int userId = rs.getInt(1 ); String userName = rs.getString(2 ); String createdBy = rs.getString(3 ); Date createdDate = rs.getDate(4 ); System.out.println("UserName : " + userId); System.out.println("UserName : " + userName); System.out.println("CreatedBy : " + createdBy); System.out.println("CreatedDate : " + createdDate); } } catch (SQLException e) { System.out.println(e.getMessage()); } finally { if (callableStatement != null ) { callableStatement.close(); } if (dbConnection != null ) { dbConnection.close(); } } } }
三,测试
执行代码结果:
select USER_INFO record!
UserName : 9
UserName : devp.com
CreatedBy : system
CreatedDate : 2017-04-02
Author:
Darren Du
License:
Copyright (c) 2019 MIT LICENSE