- jdbc总结(固定模板):
try {
- 导入驱动包,加载具体的驱动类Class.forName("具体驱动类");
- 与数据库建立连接connection=DriverManager.getConnection(..);
- 通过connection,获取操作数据库对象(Statement\preparedStatement\callablestatement)
例如:stmt=connection.createStatement();
- (查询)处理结果集rs =pstmt.executeQuery()
While(rs.next()){rs.getXxx(..);}
}catch(ClassNotFoundException e)
{...}
catch(SQLException e)
{...}
catch(Exception e)
{...}
Finally
{//打开顺序与关闭顺序相反,判断是否为空,防止空指针异常
If(rs!=null ) rs.close();
If(stmt!=null ) stmt.close();
If(connection!=null ) connection.close();
}
----jdbc中除了Class.forName()抛出ClassNotFoundException,其余方法全部抛出SQLException
- CallableStatement:调用 存储过程,存储函数
connection.prepareCall(参数:存储过程和存储函数名)
参数格式:
存储过程(无返回值return,用out参数代替 ):
{ call 存储过程名(参数表)}
存储函数(有返回值return):
{?=call 存储函数名(参数表)}
例如:创建存储过程
Create or replace procedure addTwoNum(num1 in number,num2 in number,result out number)--1+2->3
as
begin
Result :=num1+num2;
end;
/ //”/”是命令输入结束的标志;
强调:
如果通过sqlplus访问数据库,只需要开启:OracleServiceSID
通过其他程序访问数据库(sqldevelop,navicate,JDBC),需要开启:特殊的连接地址
JDBC调用存储过程的步骤:
- 产生 调用存储过程的对象(CallableStatement) cstmt =connection。prepareCall(“...”);
- 通过setXxx处理输出参数值cstmt.setInt(1,XX);
- 通过registerOutParameter(...)处理参数类型
- Cstmt .execute()执行
- 接受输出值(返回值)getXxx()
调存储函数:
create or replace function addTwoNumfunction(num1 in number,num2 in number)--1+2
return number;
as
return number;
begin
Result :=num1+num2;
Return result;
end;
/
- 处理CLOB/BLOB类型
处理稍大型数据:
- 存储路径 //文件的存储路径例如D:\JDK_API_zh_CN.CHM
通过JDBC将D:\JDK_API_zh_CN.CHM文件以字符串形式”D:\JDK_API_zh_CN.CHM”
存储到数据库中
b.
CLOB:大文本数据(小说->数据)
BLOB:二进制
Clob:
存:
- 先通过pstmt的?代替小说内容(占位符)
- 再通过pstmt.setCharacterStream(2,reader,(int)file.length());将上一步的?替换为小说流
注意编码一致
取:
- 通过Reader reader=rs.getcharacterStream (“NOVEL”);将clob类型的数据保存在Reader对象中
- 将Reader通过Writer输出即可。
Blob :二进制 字节流InputStream OutputStream
与CLOB步骤基本一致,区别:setBinaryStream(...) getBinaryStream(...)