大可制作:QQ群:31564239(asp|jsp|php|mysql)

Java Gossip: 将文件存入数据库

如果将要文件写入数据库,您可以在栏位上使用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文件来获得更详细的讯息。

下面这个程序示范基本的文件存入数据库并取出另存新档:

  • BLOBCLOBDemo.java
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的处理。