import java.sql.*;
import java.io.*;
public class UploadToDB
{
String driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
String url="jdbc:microsoft:sqlserver://localhost:1433;databaseName=fileupload";
String password="flyer";
String userName="sa";
public UploadToDB()
{
}
public Connection getConnection()
{
Connection con=null;
try
{
Driver drive=(Driver)(Class.forName(driver).newInstance());
System.out.println(drive);
System.out.println(drive.acceptsURL(url));
con=DriverManager.getConnection(url,userName,password);
}
catch(SQLException e)
{
e.printStackTrace();
}
catch(Exception ef)
{
ef.printStackTrace();
}
return con;
}
public void addFile(String filePath)
{
Connection con=this.getConnection();
try
{
PreparedStatement pst=con.prepareStatement("insert into files(wenjian) values(?)");
File file=new File(filePath);
int fileSize=(int)file.length();
InputStream fin=new FileInputStream(file);
pst.setBinaryStream(1,fin,fileSize);
pst.executeUpdate();
}catch(FileNotFoundException f){
f.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public void getFile()
{
Connection con=this.getConnection();
try
{
PreparedStatement pst=con.prepareStatement("select * from files where id=?");
pst.setInt(1,2);
ResultSet rs=pst.executeQuery();
if(rs.next())
{
InputStream is=rs.getBinaryStream(2);
File file=new File("d:/a.jpg");
OutputStream fos=new FileOutputStream(file);
byte[] bytes=new byte[1024];
int by=0;
while((by=is.read(bytes))>0)
{
fos.write(bytes,0,by);
}
is.close();
fos.close();
rs.close();
con.close();
}
else
return;
}catch(FileNotFoundException f){
f.printStackTrace();
}
catch(IOException ff)
{
ff.printStackTrace();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
UploadToDB utb=new UploadToDB();
utb.getFile();
// utb.addFile("d:/aa.jpg");
// System.out.println(utb.getConnection());
}
}
經常看見在QQ羣裏 給代碼。或問題。把文件放到數據庫中去。上面是SQL Server字段是IMages . binary也一樣的,們常常這樣做。如果不知道爲什麼要把數據放到數據庫,可放到數據庫中有什麼好處。。那上面代碼就沒有什麼意義了。究竟把文件放到那兒才合適了,這就要具體考慮到我們的程序應用環境。
放到數據庫中。第一個好處。就是安全。比單純以文件的形式放在服務上,肯定是不如放在數據庫安全。第二好處。就是系統遷移,比較方便。如果是文件。特別是文件多時候。也不知道要copy 到什麼時候。但數據庫中就不一樣。我們要做的就是改一下數據庫連接的URL,其它的什麼都不要動。弊端就是實現複雜一點點。且性能。也不能文件的形式的快。如。下載這個文件。。如果直接從數據庫把流輸出到客戶端。那頁面實在是難以控制。所以通常的做法先是在服務器記取生成這個文件,又文件的形式放在服務器上。然後根據具體應用。下載。或者瀏覽。同時。也產生了問題。當文件數據更新時。。。那個生成的文件。就會出同問題。這樣數據就不一致了。在做web應用的時候。圖片的顯示。你會發現。控制比當純給文件路徑名要複雜。但圖片管理。增修改比較方便。