java对数据库的大文件的操作(SQLServer2000)
时间:2009-11-02
编写的把文件的内容写入到数据库的代码如下
首先 建立 数据库表
id char
data image(注意此处不要用text类型 text类型与binary不兼容)
代码如下:
import java.io.*;
import java.sql.*;
public class Db {
public static void main(String[] args) {
Db ac = new Db();
String blobname = "D:\\test1.txt"; //blob文件名
String in = "insert into ";
String in1 = "(id,data) values(´0004´,?)";
String tablename = "Ss";
String sqlstr = ""; // sql 语句
sqlstr = in + tablename + in1;
ThreadUseExtends thread = new ThreadUseExtends(blobname,sqlstr);
thread.insert();
}
}
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";
//String login = "system"; // use your login here
//String password = "ti2003"; // use your password here
Connection con = DriverManager.getConnection(url);
String testLong = r1.ReadFile(filename1);
//String testLong1 = r1.ReadFile(filename2);
byte[] ba = testLong.getBytes();
System.out.println("str=" + str);
//String strSql = str; //"insert into
// orders(order_id,ric_code,siz,price,trade_datetime,status,testblob,testclob)
// values(8,′asdfjkl′,21,123.34567,sysdate,′nill逆耳′,?,?)";
PreparedStatement stm = con.prepareStatement(str);
stm.setBytes(1, ba);
//StringReader test = new StringReader(testLong1);
//stm.setCharacterStream(2, test, testLong.length());
stm.execute();
stm.close();
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}//ThreadUseExtends class
// ReadFiles class for read text!!
class ReadFiles {
public ReadFiles() {
}
//ReadFile method,read file
public String ReadFile(String FileName) {
String Name = FileName;
String File = "";
try {
FileReader ReadF = new FileReader(Name);//读文件
BufferedReader HuanChong = new BufferedReader(ReadF);//文件读缓冲.
try {
File = HuanChong.readLine();
} catch (IOException e1) {
// TODO 自动生成 catch 块
e1.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
//System.out.println("文件:"+File);
return File;
}
}//ReadFiles class
|