package com.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Types;
public class Connect {
public static void main(String[] args) {
/* JDBC连接MySQL数据库的参数 */
String driverName = "com.mysql.jdbc.Driver";
String userName = "root";
String userPasswd = "admin";
String dbName = "stopro";
String url = "jdbc:mysql://localhost/" + dbName + "?user=" + userName
+ "&password=" + userPasswd;
Connection connection = null;
CallableStatement stmt = null;
try {
// 加载数据库驱动程序
Class.forName(driverName).newInstance();
// 连接数据库
connection = DriverManager.getConnection(url);
// 调用存储过程,此存储过程有2个参数
stmt = connection.prepareCall("{call p3(?,?)}");
// 第一个参数是输入的,在此设置第一个参数的值:将第一个参数设置成整数值1
stmt.setInt(1, 1);
// 第二个参数是输出的,在此设置第二个参数的输出类型为VARCHAR
stmt.registerOutParameter(2, Types.VARCHAR);
// 执行存储过程
boolean hadResults = stmt.execute();
// 如果有查询语句的话,此执行过程会返回结果集,在此处理结果集里面的东西
System.out.println("Data from table:");
while (hadResults) {
ResultSet rs = stmt.getResultSet();
while(rs.next()){
String id = rs.getString(1);
String name = rs.getString(2);
System.out.println("ID = "+id+"\tName = " + name);
}
hadResults = stmt.getMoreResults();
}
// 获取存储过程的返回值
System.out.println("\nData from procedure:");
String name = stmt.getString(2); // 获得第二个参数,因为第二个参数是输出类型的
System.out.println("Name = " + name);
}
catch (Exception e) {
System.out.println(e.toString());
}
finally {
try {
stmt.close();
connection.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
}
1
顶
0
踩
分享到:
2011-12-14 11:09
浏览 1366
评论