import java.sql.*;
public class DBDeclareTest{
private Connection con = null;// 数据库连接
private java.sql.CallableStatement cs = null;//执行存储过程的接口
private int key;
private String name;
//在构造函数中构造连接
public DBDeclareTest(){
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = DriverManager.getConnection("jdbc:microsoft:sqlserver://127.0.0.1:1433;databasename=pubs","sa","");
System.out.println ("con ok");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
//调用无返回值的存储过程
public void getOK1(){
try {
String sql="{call pro_mypro1(?,?)}";
cs = con.prepareCall(sql);
cs.setInt(1,key);
cs.setString(2,name);
cs.executeUpdate();
System.out.println ("执行成功,可以休息了。。。。");
cs.close();
con.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
//调用有返回值的存储过程
public void getOK2(){
try {
String sql = "{call pro_mypro2(?,?)}";
cs = con.prepareCall(sql);
//设置output外部传参
cs.registerOutParameter(1,java.sql.Types.BIT);
cs.setString(2,name);
cs.execute();
//获得output外部传参的值
int numOut = cs.getInt(1);
if(numOut ==1){
System.out.println ("数据表存在");
}else{
System.out.println ("数据表不存在!!!");
}
cs.close();
con.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
//返回结果集的存储过程
public void getOK3(){
try {
String sql = "{call pro_mypro3(?,?)}";
cs = con.prepareCall(sql);
//设置output外部传参
cs.registerOutParameter(1,java.sql.Types.BIT);
cs.setString(2,name);
boolean flag = cs.execute();
System.out.println (flag);
if(flag){
System.out.println ("OKOKOKO");
ResultSet rs = cs.getResultSet();
ResultSetMetaData rsmd =rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while(rs.next()){
for(int i=0;i<numberOfColumns;i++)
{
System.out.println (rsmd.getColumnName(i)+" ");
System.out.println (rs.getObject(i)+" ");
}
}
}else
{
System.out.println ("表名不存在:"+cs.getBoolean(1));
}
cs.close();
con.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void setKey(int k){
this.key = k;
}
public int getKey(){
return this.key;
}
public void setName(String n){
this.name = n;
}
public String getName(){
return this.name;
}
}