|
下面是一个java连接Oracle 执行一个没有返回值的存储过程的小例程。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
| package com.test;
import java.sql.*;
public class procedure {
public static void main(String[] args) {
Connection ct=null;
CallableStatement cs=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
ct=DriverManager.getConnection("jdbc:oracle:thin:@10.8.2.73:1521:orcl",
"scott","123456");
cs=ct.prepareCall("{call pro_book(?,?,?)}");
cs.setInt(1, 10001);
cs.setString(2, "华尔街之狼");
cs.setString(3, "中信出版社");
cs.execute();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
cs.close();
ct.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
|
下面是java执行一个有返回值的存储过程的小程序。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| package com.test;
import java.sql.*;
public class procedure {
public static void main(String[] args) {
Connection ct=null;
CallableStatement cs=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
ct=DriverManager.getConnection("jdbc:oracle:thin:@10.8.2.73:1521:orcl",
"scott","123456");
cs=ct.prepareCall("{call pro_book_getname(?,?)}");
cs.setInt(1, 10001);
cs.registerOutParameter(2, oracle.jdbc.OracleTypes.VARCHAR);
cs.execute();
String name=cs.getString(2);
System.out.println(name);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
cs.close();
ct.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
|
一个取得一个集合的java程序:
首先先写一个oracle包,定义一个cursor类型,PL/SQL如下:
1
2
3
4
| create package pack_cursor is
type type_cursor is ref cursor;
end;
/
|
再写一个存储过程:
1
2
3
4
5
| create or replace procedure pro_emp_cursor(no in number,cur out pack_cursor.type_cursor) is
begin
open cur for select * from emp where deptno=no;
end;
/
|
java程序代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| package com.test;
import java.sql.*;
public class procedure {
public static void main(String[] args) {
Connection ct=null;
CallableStatement cs=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
ct=DriverManager.getConnection("jdbc:oracle:thin:@10.8.2.73:1521:orcl",
"scott","123456");
cs=ct.prepareCall("{call pro_emp_cursor(?,?)}");
cs.setInt(1, 10);
cs.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
cs.execute();
ResultSet rs=(ResultSet)cs.getObject(2);
while(rs.next())
{
System.out.println("EMPNO:"+rs.getInt(1)+" NAME:"+rs.getString(2)+" JOB:"+rs.getString(3));
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
cs.close();
ct.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
|
|
|