📄 wandrblob.java
字号:
package wandrblob;
import java.io.*;
import java.util.*;
import java.sql.*;
import oracle.jdbc.driver.*;
import java.text.*;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class WandRBlob {
private static Object pstmt;
public static void main(String[] args){
/**
*第一步,装载驱动程序,但要注意处理异常;
**/
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
/**
*第二步,建立数据库连接;
**/
String url = "jdbc:oracle:thin:@192.168.0.7:1521:certdb";
String user = "certdb";
String password = "certdb";
Connection conn = DriverManager.getConnection(url,user,password);
/**
*第三步,让数据库准备好接收数据;
**/
String sql1 = "INSERT INTO BLOBTEST(NAME,SEX,ADDRESS,KEY) VALUES(?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(sql1);
/**
*第四步,把准备写入数据库的大型文件做成数据流,注意异常的处理,并将此数据流写入一个缓冲;
**/
String strFile = "D:\\chensong.crt";
File inFile = new File(strFile);
FileInputStream inputStreamFile = new FileInputStream(inFile);//得到数据流;
byte[] buffer = new byte[(int)inFile.length()];
inputStreamFile.read(buffer);//此数据流写入一个缓冲;
/**
* 第五步,写入数据库,注意将流关闭;
* */
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(buffer);
//将缓冲中的数据变成字节流,此字节流将用来写入数据库;
pstmt.setString(1,inFile.getName());
pstmt.setString(2,"pwoman");
pstmt.setString(3,"国防科技大学");
pstmt.setBinaryStream(4,byteArrayInputStream,(int)inFile.length());//写入Blob数据;
pstmt.execute();//开始执行操作;
inputStreamFile.close();//关闭流;
byteArrayInputStream.close();//关闭流;
pstmt.close();//关闭数据库的写入状态;
//////////////////////////////////////////////////////////////////////////////////
/*下面将数据从数据库中读出来,并写入另一个文件*/
//////////////////////////////////////////////////////////////////////////////////
/**
*第六步,让数据库做好写出数据的准备;
**/
//String str = inFile.getName();
// String sql2 = "SELECT KEY FROM BLOBTEST WHERE SEX = 'pwoman'";
String sql2 = "SELECT KEY FROM BLOBTEST";
PreparedStatement pstmt2 = conn.prepareStatement(sql2);
ResultSet resultSet = pstmt2.executeQuery();//执行查询,返回结果集;
/**
*第七步,对查询结果进行操作;
**/
int byteRead = 0;
byte[] bufferWrite = new byte[19240];
FileOutputStream fileOutputStream = new FileOutputStream("F:\\crt.crt");
if(resultSet != null){
resultSet.next();
InputStream inputStream = resultSet.getBinaryStream(1);
while((byteRead = inputStream.read(bufferWrite)) != -1){
fileOutputStream.write(bufferWrite, 0, byteRead);
}
/**
*第八步,关闭流,以及各种连接;
**/
inputStream.close();
}
fileOutputStream.close();
pstmt2.clearBatch();
conn.close();
}catch(IOException ioE){
System.out.println(ioE.getMessage());
ioE.getStackTrace();
}catch(SQLException sqlex){
System.out.println(sqlex.getMessage());
}catch(Exception ex){
System.out.println(ex.getMessage());
ex.getStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -