As代碼:
JAVA代碼:
import java.io.*;
import java.sql.*;
import com.qiansoft.util.ByteImage;
public class PutImg {
public void putimg(byte img []) {
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=TestImg";
Connection conn = DriverManager.getConnection(url,"sa","876010");
Statement stmt = conn.createStatement();
stmt.close();
PreparedStatement pstmt = null;
String sql = "";
sql = "INSERT INTO imgtable (img) VALUES (?)";
pstmt = conn.prepareStatement(sql);
pstmt.setBinaryStream(1, ByteImage.getStreamFromByte(img), (int) img.length);
pstmt.executeUpdate();
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
ByteImage代碼:
import java.io.*;
import java.sql.*;
public class ByteImage {
//用于將從數(shù)據(jù)庫中讀取的二進制文件流轉(zhuǎn)換為byte數(shù)組
public static byte [] getByteFromStream(InputStream is){
byte[] b = new byte [1];
try {
ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
//創(chuàng)建數(shù)據(jù)讀取緩存byte數(shù)組
byte[] buffer = new byte[2048];
int temp;
if(is == null)
return null;
temp = is.read(buffer);
while (temp != -1) {
bytestream.write(buffer, 0, temp);
temp = is.read(buffer);
}
//將ByteArrayOutputStream轉(zhuǎn)換為二進制數(shù)組
b = bytestream.toByteArray();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
public static InputStream getStreamFromByte(byte img []){
return new ByteArrayInputStream(img);
}
}