在做项目的过程中,经常需要调用数据库的存储过程,试着写了一下简单的例子,记录下。
存储过程(oracle):
1) 无参存储过程
create or replace procedure firPro
as
begin
dbms_output.put_line('Hello World!');
end;
java调用:
public static void noPramPro()
{
Connection con=DButil.getConnection();
try {
CallableStatement stmt = con.prepareCall("{call firPro()}");
stmt.execute();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2)有参存储过程:
create or replace procedure Ins_Pro
(stuNO in varchar,stuName in varchar,stuGender in varchar,
stuAge in varchar,stuSeat in varchar, enrolldate in date,stuAddress in varchar,classNo in varchar)
as
begin
insert into student values(stuNO,stuName,stuGender,stuAge,stuSeat,enrolldate,stuAddress,classNo);
commit;
end;
java 调用:
public static void insertPro()
{
try {
Connection con = DButil.getConnection();
CallableStatement stmt = con.prepareCall("{call Ins_Pro(?,?,?,?,?,?,?,?)}");
stmt.setString(1, "9");
stmt.setString(2, "张三丰");
stmt.setString(3, "男");
stmt.setString(4, "90");
stmt.setString(5, "55");
stmt.setDate(6, new Date(0));
stmt.setString(7, "武当山");
stmt.setString(8, "9");
stmt.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
3)有输出的存储过程:
create or replace procedure selPro(stuNO in varchar,name out varchar,address out varchar)
as
begin
select stu_name,stu_address into name,address from student where stu_no = stuNO;
end;
java调用:
public static void selPro()
{
Connection con = DButil.getConnection();
try {
CallableStatement stmt = con.prepareCall("{call selPro(?,?,?)}");
stmt.setString(1, "3");
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
stmt.registerOutParameter(3, java.sql.Types.VARCHAR);
stmt.execute();
String name =stmt.getString(2);
String address = stmt.getString(3);
System.out.println(name +"------"+address);
} catch (SQLException e) {
e.printStackTrace();
}
}