import java.io.*;
import java.sql.*;
public class Db {
public static void main(String[] args) {
Db ac = new Db();
String blobname = "D:\\test1.jpg"; //blob文件名
String in = "insert into ";
String in1 = "(id,data) values(´0012´,?)";
String tablename = "Ss";
String sqlstr = ""; // sql 語句
sqlstr = in + tablename + in1;
ThreadUseExtends thread = new ThreadUseExtends(blobname,sqlstr);
thread.insert();
thread.getCover();
}
}
class ThreadUseExtends {
String filename1;//blob filename
String str;
//ReadFiles r1 = new ReadFiles();
//構造函數要有(blob文件名,clob文件名,sql語句)
public ThreadUseExtends(String name1,String sqlstr)
{
filename1 = name1;
str = sqlstr;
System.out.println("I carry out this");
}
public void insert()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:LW";
Connection con = DriverManager.getConnection(url);
//String testLong = r1.ReadFile(filename1);
File file=new File(filename1);
InputStream fin=new FileInputStream(file);
int fileLength=(int)file.length();
//byte[] ba = testLong.getBytes();
System.out.println("str=" + str);
PreparedStatement stm = con.prepareStatement(str);
stm.setBinaryStream(1,fin,fileLength);
stm.execute();
stm.close();
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
//本函數用於把數據庫的內容從數據庫中讀出,並保存在文件中。
public void getCover() {
InputStream in=null;
Connection cn = null;
PreparedStatement pst = null;
byte buf[]=new byte[50000];
DataOutputStream output=null;
int size;
System.out.println("have carry out this");
try
{
output=new DataOutputStream(new FileOutputStream("D:\\test2.jpg"));
}
catch(IOException e)
{
System.err.println("File not opened \n"+e.toString());
System.exit(1);
}
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:LW";
cn = DriverManager.getConnection(url);
pst=cn.prepareStatement("SELECT data FROM Ss where ID =´0012´");
// pst.setString(1,id);
ResultSet rs=pst.executeQuery();
while(rs.next())
{
in=rs.getBinaryStream("data");
while ((size=in.read(buf,0,50000))!=-1) {
output.write(buf,0,size);
}
}
}
catch (SQLException sqle) {
System.err.println("Error in CoverServlet : getCover()-" + sqle);
sqle.printStackTrace() ;
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
try {
pst.close() ;
cn.close() ;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}//ThreadUseExtends class