package?demo.utils;
import?java.sql.Connection;
import?java.sql.DriverManager;
import?java.sql.ResultSet;
import?java.sql.SQLException;
import?java.sql.Statement;
public?class?JDBCUtils?{
private?static?String?driver?=?"oracle.jdbc.OracleDriver";
private?static?String?url?=?"jdbc:oracle:thin:@localhost:zhang0519";
private?static?String?user?=?"scott";
private?static?String?password?=?"tiger";
//注冊數(shù)據(jù)庫驅(qū)動
static{
try?{
Class.forName(driver);
}?catch?(ClassNotFoundException?e)?{
throw?new?ExceptionInInitializerError(e);
}
}
//獲取數(shù)據(jù)庫連接
public?static?Connection?getConnection(){
try?{
return?DriverManager.getConnection(url,user,password);
}?catch?(SQLException?e)?{
e.printStackTrace();
}
return?null;
}
//釋放數(shù)據(jù)庫的資源
public?static?void?release(Connection?conn,Statement?st,ResultSet?rs){
if(rs?!=?null){
try?{
rs.close();
}?catch?(SQLException?e)?{
e.printStackTrace();
}finally{
rs?=?null;
}
}
if(st?!=?null){
try?{
st.close();
}?catch?(SQLException?e)?{
e.printStackTrace();
}finally{
st?=?null;
}
}
if(conn?!=?null){
try?{
conn.close();
}?catch?(SQLException?e)?{
e.printStackTrace();
}finally{
conn?=?null;
}
}
}
}
package?demo.oracle;
import?java.sql.CallableStatement;
import?java.sql.Connection;
import?org.junit.Test;
import?demo.utils.JDBCUtils;
import?oracle.jdbc.driver.OracleTypes;
public?class?TestProcedure?{
@Test
public?void?testProcedure(){
String?sql?=?"{call?queryempinf(?,?,?,?)}";
Connection?conn?=?null;
CallableStatement?call?=?null;
try?{
//得到一個連接
conn?=?JDBCUtils.getConnection();
//通過連接創(chuàng)建Statement
call?=?conn.prepareCall(sql);
//對于in參數(shù),賦值
call.setInt(1,7839);
//對于out參數(shù),申明
call.registerOutParameter(2,?OracleTypes.VARCHAR);
call.registerOutParameter(3,?OracleTypes.NUMBER);
call.registerOutParameter(4,?OracleTypes.VARCHAR);
//執(zhí)行調(diào)用
call.execute();
//取出結(jié)果
String?name?=?call.getNString(2);
double?sal?=?call.getDouble(3);
String?job?=?call.getNString(4);
System.out.println(name+"\t"+sal+"\t"+job);
}?catch?(Exception?e)?{
e.printStackTrace();
}finally{
JDBCUtils.release(conn,?call,?null);
}
}
}
2016-07-03
你的URL設(shè)置的有問題:private?static?String?url?=?"jdbc:oracle:thin:@localhost:zhang0519";
這個是我本地的:private static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
注意格式:jdbc:oracle:thin:@localhost:端口號:數(shù)據(jù)庫名 ? ?注意這里的漢字部分,且是以冒號隔開的
2016-06-17