扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
方法如下:importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;/***LoadJDBCDriver*最基本的方法通过JDBC连接数据库*@authorJacob**/publicclassLoadByPrimary{publicstaticvoidmain(String[]args)throwsClassNotFoundException{Stringdriver="oracle.jdbc.OracleDriver";Connectioncn=null;/***Class.forName手动加载一个类到方法区,Driver类中包含自动注册驱动的静态代码块*会自动在DriverManager中注册驱动*/Class.forName(driver);Stringurl="jdbc:oracle:thin:@localhost:1521:ORACLE";//1521代表端口号,默认的Stringuser="用户名";Stringpwd="密码";try{/**Connection是接口,返回值是一个引用对象,是Oracle驱动提供实现类ojdbc7.jar*使用JDBCAPI接口,实际上是驱动实现类*/cn=DriverManager.getConnection(url,user,pwd);Statementstmt=cn.createStatement();Stringsql="SELECT*FROMstu_empWHEREdeptno=10";ResultSetrs=stmt.executeQuery(sql);while(rs.next()){System.out.println(rs.getInt("empno")+""+rs.getString("ename")+""+rs.getString("job"));}rs.close();stmt.close();}catch(SQLExceptione){e.printStackTrace();}finally{try{if(cn!=null){cn.close();}}catch(SQLExceptione2){e2.printStackTrace();}}}}这是通过preparedstatement实现更新数据,这里我把连接数据库的方法进行了封装,每次直接调用了。publicstaticvoidmain(String[]args){PreparedStatementDemopsd=newPreparedStatementDemo();psd.updateSalary("JACOB",3000);psd.selectSalary("JACOB");}publicvoidupdateSalary(Stringename,doublesal){Stringsql="Updatestu_empsetsal=?Whereename=?";Connectioncn=null;PreparedStatementps=null;try{cn=DBPUtil.getConnection();ps=cn.prepareStatement(sql);ps.setDouble(1,sal);ps.setString(2,ename);intnum=ps.executeUpdate();System.out.println("提示:总共有"+num+"条数据已经更新!");}catch(SQLExceptione){e.printStackTrace();}finally{DBUtil.stmtClose(ps);DBUtil.connClose(cn);}}publicvoidselectSalary(Stringname){Stringsql="Select*Fromstu_empWhereename=?";Connectioncn=null;PreparedStatementps=null;ResultSetrs=null;try{cn=DBPUtil.getConnection();ps=cn.prepareStatement(sql);ps.setString(1,name);rs=ps.executeQuery();while(rs.next()){System.out.println(rs.getString("ename")+"的工资是:"+rs.getInt("sal"));}}catch(SQLExceptione){e.printStackTrace();}finally{DBUtil.stmtClose(ps);DBUtil.rsClose(rs);DBUtil.connClose(cn);}}}
站在用户的角度思考问题,与客户深入沟通,找到思明网站设计与思明网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站设计、做网站、企业官网、英文网站、手机端网站、网站推广、域名申请、虚拟主机、企业邮箱。业务覆盖思明地区。
java代码:
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager
.getConnection("jdbc:mysql://localhost:3306/test?user=rootpassword=111111");
String sql = "{call sel(?)}";
CallableStatement cs = (CallableStatement)con.prepareCall(sql);
cs.execute();
String name = cs.getString(1);
System.out.println(name);
创建存储过程代码:
drop procedure if exists sel;
create procedure sel(out name1 varchar(225))
begin
select name into name1 from a limit 1;
end
输出结果:
这是我以前的学习笔记,LZ凑合着看看吧,应该能看懂一些吧
===================================================
55 java跟oracle 调用(存储过程,函数等)
55.1 Java调用无参的函数
1:函数为:
create or replace function MyF1 return varchar2 is
Result varchar2(20);
begin
dbms_output.put_line('now in My F1');
Result := 'Now MyF1 return';
return(Result);
end MyF1;
2:Java程序
/**
* 演示调用有一个没有参数的函数
* @throws Exception
*/
private static void t1() throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:orcl", "test", "test");
try {
CallableStatement stmt = conn
.prepareCall("{?=call MyF1()}");
stmt.registerOutParameter(1, Types.VARCHAR);
stmt.execute();
System.out.println(stmt.getString(1));
} finally {
conn.close();
}
}
55.2 Java调用无参但有返回值的存储过程
1:存储过程
create or replace procedure MyP1(str out Varchar2) is
begin
dbms_output.put_line('Hello Procedure.');
str :='Haha,Hello Procedure';
end MyP1;
2:程序
/**
* 如何调用无参但有返回值的存储过程 测试的存储过程
* @throws Exception
*/
private static void t2() throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:orcl", "test", "test");
try {
CallableStatement stmt = conn.prepareCall("{call MyP1(?)}");
// 注意,这里的stmt.getInt(1)中的数值1并非任意的,而是和存储过程中的out列对应的,
// 如果out是在第一个位置,那就是 stmt.getInt(1),如果是第三个位置,就是getInt.getInt(3),
// 当然也可以同时有多个返回值,那就是再多加几个out 参数了。
stmt.registerOutParameter(1, Types.VARCHAR);
stmt.execute();
System.out.println(stmt.getString(1));
} finally {
conn.close();
}
}
55.3 Java调用有参的(传入)函数
1:函数
create or replace function MyF2(a number,b varchar2) return varchar2 is
Result varchar2(50);
begin
dbms_output.put_line('a==='||a||',b=='||b);
Result := a||b;
return(Result);
end MyF2;
2:程序
/**
* 调用有参的函数
* @throws Exception
*/
private static void t3() throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:orcl", "test", "test");
try {
CallableStatement stmt = conn
.prepareCall("{?=call MyF2(?,?)}");
stmt.setInt(2, 15);
stmt.setString(3, "HelloF2");
stmt.registerOutParameter(1, Types.VARCHAR);
stmt.execute();
System.out.println(stmt.getString(1));
} finally {
conn.close();
}
}
55.4 Java调用有参的(传入传出)存储过程
1:存储过程
create or replace procedure MyP2(a in number,b in varchar2,c out varchar2) is
begin
dbms_output.put_line('a=='||a||',b=='||b);
c := 'ret=='||a||',b=='||b;
end MyP2;
2:程序
/**
* 调用有参数和返回值的存储过程
* @throws Exception
*/
private static void t4() throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:orcl", "test", "test");
try {
CallableStatement stmt = conn.prepareCall("{call MyP2(?,?,?)}");
stmt.setInt(1, 5);
stmt.setString(2, "测试");
stmt.registerOutParameter(3, Types.VARCHAR);
stmt.execute();
System.out.println(stmt.getString(3));
} finally {
conn.close();
}
}
55.5 Java向存储过程传入传出对象的数组
1:在数据中创建对象
create or replace type UserModel as object(
uuid varchar2(20),
name varchar2(20)
);
2:在数据库中建立对象的集合类型
create or replace type userCol as table of UserModel;
create or replace type retUserCol as table of UserModel;
3:在数据库中建立包
包头:
create or replace package MyTestPackage is
TYPE dbRs IS REF CURSOR;
procedure MyP3(a1 in userCol,a2 out dbRs);
end MyTestPackage;
包体:
create or replace package body MyTestPackage is
procedure MyP3(a1 in userCol,a2 out dbRs) as
umCol retUserCol := retUserCol();
begin
for i in 1.. a1.count loop
insert into tbl_test values (a1(i).uuid,a1(i).name);
end loop;
commit;
umCol.Extend;
umCol(1):=UserModel('retUuid11','retName11');
umCol.Extend;
umCol(2):=UserModel('retUuid22','retName22');
open a2 for select * from table(cast(umCol as retUserCol));
end;
begin
null;
end MyTestPackage;
4:程序:
/**
* 测试向pl/sql传入对象集合,从pl/sql返回任意的对象的集合
* @param list
* @throws Exception
*/
private static void t5(List list) throws Exception {
CallableStatement stmt = null;
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:@127.0.0.1:1521:orcl", "test", "test");
if (con != null) {
ARRAY aArray = getArray(con, "USERMODEL", "USERCOL", list);//该函数调用的第二三个参数必须大写
stmt = con.prepareCall("{call MyTestPackage.MyP3(?,?)}");
((OracleCallableStatement) stmt).setARRAY(1, aArray);
stmt.registerOutParameter(2, OracleTypes.CURSOR);
stmt.execute();
ResultSet rs=(ResultSet)stmt.getObject(2);
while(rs.next()){
String uuid = rs.getString("uuid");
String name = rs.getString("name");
System.out.println("the uuid="+uuid+",name="+name);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static ARRAY getArray(Connection con, String OracleObj, String Oraclelist,
List objlist) throws Exception {
ARRAY list = null;
if (objlist != null objlist.size() 0) {
StructDescriptor structdesc = new StructDescriptor(OracleObj, con);
STRUCT[] structs = new STRUCT[objlist.size()];
Object[] result = new Object[0];
for (int i = 0; i objlist.size(); i++) {
result = new Object[2];//数组大小应和你定义的数据库对象(UserModel)的属性的个数
result[0] = ((UserModel)(objlist.get(i))).getUuid(); //将list中元素的数据传入result数组
result[1] = ((UserModel)(objlist.get(i))).getName(); //
structs[i] = new STRUCT(structdesc, con, result);
}
ArrayDescriptor desc = ArrayDescriptor.createDescriptor(Oraclelist,
con);
list = new ARRAY(desc, con, structs);
}
return list;
}
如果使用Tomcat的DBCP的连接池,需要把连接进行转换
public Connection getNativeConnection(Connection con) throws SQLException {
if (con instanceof DelegatingConnection) {
Connection nativeCon = ((DelegatingConnection) con).getInnermostDelegate();
return (nativeCon != null ? nativeCon : con.getMetaData().getConnection());
}
return con;
}
//存储过程create or replace Procedure countBySal(
p_sal emp.sal%type,
p_count OUT number
)as
begin
select count(*) into p_count from emp where sal = p_sql;
end countBySal; //调用步奏import java.sql.CallableStatement; //带哦用存储过程所必须的语句借口
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;public class EmpUtil {
public static int countBySal(double sal) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
String "jdbc:oracle:thin:@localhost:1521:test";
Connection cn=DriverManager.getConnection(url, "scott", "tiger");
String sql="{call countBySal(?,?)}";//调用存储过程的语句,call后面的就是存储过程名和需要传入的参数
CallableStatement cst=cn.prepareCall(sql);
cst.setDouble(1, sal);//设置in参数的值
cst.registerOutParameter(2, Types.INTEGER);//注册out参数的类型
cst.execute();
int result = cst.getInt(2);
cst.close();
cn.close();
return result;
}
public static void main(String[] args) {
int count;
try {
count = EmpUtil.countBySal(3000);
System.out.println("工资在3000元以上的人数为:"+count);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java调用存储过程的方法是通过调用Connection的实例方法prepareCall,prepareCall方法返回CallableStatement对象用于填充存储过程的参数。prepareCall方法形参是调用存储过程的sql语句,此参数的语法格式如下:
{call storedProcedureName(parameter-list)}
其中,storedProcedureName是存储过程名称,parameter-list是存储过程参数列表。
例如,存储过程名为usp_test,有两个输入参数a,b。则调用代码看起来如下所示:
CallableStatement callableStatement = connection.prepareCall("{call usp_test(?,?)}");
callableStatement.setObject("a","value-1");
callableStatement.setObject("b","value-2");
callableStatement.execute();
JDBC调用存储过程: CallableStatement
在Java里面调用存储过程,写法那是相当的固定:
Class.forName(....
Connection conn = DriverManager.getConnection(....
/**
*p是要调用的存储过程的名字,存储过程的4个参数,用4个?号占位符代替
*其余地方写法固定
*/
CallableStatement cstmt = conn.prepareCall("{call p(?,?,?,?)}");
/**
*告诉JDBC,这些个参数,哪些是输出参数,输出参数的类型用java.sql.Types来指定
*下面的意思是,第3个?和第4个?是输出参数,类型是INTEGER的
*Types后面具体写什么类型,得看你的存储过程参数怎么定义的
*/
cstmt.registerOutParameter(3, Types.INTEGER);
cstmt.registerOutParameter(4, Types.INTEGER);
/**
*在我这里第1个?和第2个?是输入参数,第3个是输出参数,第4个既输入又输出
*下面是设置他们的值,第一个设为3,第二个设为4,第4个设置为5
*没设第3个,因为它是输出参数
*/
cstmt.setInt(1, 3);
cstmt.setInt(2, 4);
cstmt.setInt(4, 5);
//执行
cstmt.execute();
//把第3个参数的值当成int类型拿出来
int three = cstmt.getInt(3);
System.out.println(three);
//把第4个参数的值当成int类型拿出来
int four = cstmt.getInt(4);
System.out.println(four);
//用完别忘给人家关了,后开的先关
cstmt.close();
conn.close();
JDBC调用存储过程,掌握这一个程序足够了.
以下是上面程序使用的存储过程的代码,我用的是Oracle数据库,不过不论是什么数据库,对于你的程序,JDBC这一端写法都是一样的.
create or replace procedure p
(v_a in number,v_b number,v_ret out number,v_temp in out number)
is
begin
if(v_a v_b) then
v_ret := v_a;
else
v_ret := v_b;
end if;
v_temp := v_temp + 1;
end;
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流