如果将要档案写入数据库,您可以在字段上使用BLOB或CLOB数据型态,BLOB全名Binary Large Object,用于储存大量的二进制数据,CLOB全名Character Large Object,用于储存大量的文字数据。
在JDBC中也提供了Blob与Clob两个类别分别代表BLOB与CLOB资料,您可以使用PreparedStatement的setBinaryStream()、 setObject()、setAsciiStream()、setUnicodeStream()等方法来代替,例如我们可以如下取得一个档案,并将之存入数据库中:
// 取得档案
File file = new File("./logo_phpbb.jpg");
int length = (int) file.length();
InputStream fin = new FileInputStream(file);
// 填入数据库
PreparedStatement pstmt = conn.prepareStatement(
"INSERT INTO files VALUES(?, ?)");
pstmt.setString(1, "米小国Logo");
pstmt.setBinaryStream (2, fin, length);
pstmt.executeUpdate();
pstmt.clearParameters();
pstmt.close();
fin.close();
如果要从数据库中取得BLOB或CLOB资料,您可以如下进行:
Blob blob = result.getBlob(2);?// 取得BLOB Clob clob = result.getClob(2)?// 取得CLOB?
Blob拥有getBinaryStream()、getBytes()等方法,可以取得二进制串流或byte等数据,同样的,Clob拥有getCharacterStream()、getSubString()等方法,可以取得字符串流或子字符串等数据,您可以查看API文件来获得更详细的讯息。
下面这个程序示范基本的档案存入数据库并取出另存新档:
package onlyfun.caterpillar;
import java.io.*;
import java.sql.*;
public class BLOBCLOBDemo {
public static void main(String[] args) {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/upload?" +
"useUnicode=true&characterEncoding=Big5";
String user = "caterpillar";
String password = "123456";
try {
Class.forName(driver);
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = DriverManager.getConnection(
url, user, password);
// 取得档案
File file = new File("./logo_phpbb.jpg");
int length = (int) file.length();
InputStream fin = new FileInputStream(file);
// 填入数据库
pstmt = conn.prepareStatement(
"INSERT INTO files VALUES(?, ?)");
pstmt.setString(1, "米小国Logo");
pstmt.setBinaryStream (2, fin, length);
pstmt.executeUpdate();
pstmt.clearParameters();
fin.close();
}
catch(SQLException e) {
e.printStackTrace();
}?
catch(IOException e) {
e.printStackTrace();
}
finally {
if(pstmt != null) {
try {
pstmt.close();
}?
catch(SQLException e) {
e.printStackTrace();
}
}
}
Statement stmt = null;
try {
// 从数据库取出档案
stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(
"SELECT * FROM files");
result.next();
String description = result.getString(1);
Blob blob = result.getBlob(2);
// 写入档案
System.out.println("档案描述:" + description);
FileOutputStream fout =
new FileOutputStream("./logo_phpbb_2.jpg");
fout.write(blob.getBytes(1, (int)blob.length()));
fout.flush();
fout.close();
}
catch(SQLException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
finally {
if(stmt != null) {
try {
stmt.close();
}?
catch(SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
}
catch(SQLException e) {
e.printStackTrace();
}
}
}
}
catch(ClassNotFoundException e) {
System.out.println("找不到驱动程序");
e.printStackTrace();
}
}
}
您还可以参考 串流资料型别 中有关于BLOB的处理。