首先我创建一个过程
package procedure;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Pro2 {
enter code herestatic String className = "com.mysql.jdbc.Driver";
static String url = "jdbc:mysql://localhost:3306/testdb";
static String user = "root";
static String password = "";
public static void main(String[] args) {
Connection con;
Statement stmt;
try {
String drop2 = "DROP PROCEDURE IF EXISTS au2;";
String query2 = ""
+ "CREATE PROCEDURE au2(\n"
+ " INOUT id VARCHAR(11),\n"
+ " OUT fname VARCHAR(20),\n"
+ " OUT lname VARCHAR(40),\n"
+ " OUT phone VARCHAR(12),\n"
+ " OUT address VARCHAR(100),\n"
+ " OUT city VARCHAR(20),\n"
+ " OUT state VARCHAR(20),\n"
+ " OUT zip VARCHAR(5)\n"
+ ")\n"
+ "BEGIN\n"
+ " SELECT * FROM author WHERE au_id = id ; \n"
+ "END";
Class.forName(className);
con = DriverManager.getConnection(url, user, password);
stmt = con.createStatement();
stmt.executeUpdate(drop2);
stmt.executeUpdate(query2);
stmt.close();
con.close();
} catch (ClassNotFoundException | SQLException e) {
System.err.println("Error: "+e.getMessage());
}
}
}
然后我叫它,但是我得到了除id以外的所有空值
package procedure;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;
public class CallPro2 {
static String className = "com.mysql.jdbc.Driver";
static String url = "jdbc:mysql://localhost:3306/testdb";
static String user = "root";
static String password = "";
public static void main(String[] args) {
Connection con;
String query2 = "{call au2(?,?,?,?,?,?,?,?)}";
try {
Class.forName(className);
con = DriverManager.getConnection(url, user, password);
CallableStatement cstmt = con.prepareCall(query2);
cstmt.setString(1, "A00001");
cstmt.registerOutParameter(2, Types.VARCHAR);
cstmt.registerOutParameter(3, Types.VARCHAR);
cstmt.registerOutParameter(4, Types.VARCHAR);
cstmt.registerOutParameter(5, Types.VARCHAR);
cstmt.registerOutParameter(6, Types.VARCHAR);
cstmt.registerOutParameter(7, Types.VARCHAR);
cstmt.registerOutParameter(8, Types.VARCHAR);
cstmt.execute();
System.out.println(""
+ "Author ID: "+cstmt.getString(1)+"\n"
+ "First name: " + cstmt.getString(2) + "\n"
+ "Last name: " + cstmt.getString(3) + "\n"
+ "Phone: " + cstmt.getString(4) + "\n"
+ "Address: " + cstmt.getString(5) + "\n"
+ "City: " + cstmt.getString(6) + "\n"
+ "State: " + cstmt.getString(7) + "\n"
+ "Zipcode: " + cstmt.getString(8));
con.close();
} catch (SQLException | ClassNotFoundException e) {
System.err.println("Error: " + e.getMessage());
}
}
}
我像这样运行程序时的结果:
Author ID: A00001
First name: null
Last name: null
Phone: null
Address: null
City: null
State: null
Zipcode: null
BUILD SUCCESSFUL (total time: 1 second)