我們知道可以把二進制數(shù)據(jù)存進數(shù)據(jù)庫里去,可是沒做過哦!
前兩天一網(wǎng)友問題怎么做?才去查一下資料,試驗了一下
//Create.java
import java.sql.*;
public class Create {
public static void main(String[] args) {
Connection con;
Statement st;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=C:\\Test\\data.mdb";
con = DriverManager.getConnection(url, "", "");
st = con.createStatement();
st.execute("CREATE TABLE mytable(id autoincrement, picname varchar(50), pic image);");
//我用 Access 做下簡單測試, Oracle 數(shù)據(jù)庫用 "CREATE TABLE mytable(id autoincrement, picname varchar(50), pic BLOB);" 建表
st.close();
con.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
// SavePic.java 將圖片保存至數(shù)據(jù)庫
import java.sql.*;
import java.io.*;
public class SavePic {
public static void main(String[] args) {
Connection con;
PreparedStatement st;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=C:\\Test\\data.mdb";
con = DriverManager.getConnection(url, "", "");
String sql = "INSERT INTO mytable(picname, pic) values('雅林',?)";
st = con.prepareStatement(sql);
File f = new File("C:/Test/a.jpg");
FileInputStream fis = new FileInputStream(f);
st.setBinaryStream(1, fis, (int)f.length());
st.executeUpdate();
st.close();
con.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
//ReadPic.java 從數(shù)據(jù)庫中讀出圖片存成文件
import java.sql.*;
import java.io.*;
public class ReadPic {
public static void main(String[] args) {
Connection con;
Statement st;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=C:\\Test\\data.mdb";
con = DriverManager.getConnection(url, "", "");
String sql = "SELECT pic FROM mytable WHERE picname='雅林'";
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
rs.next();
File f = new File("C:/Test/b.jpg");
FileOutputStream fos = new FileOutputStream(f);
InputStream is = rs.getBinaryStream("pic");
int c;
byte b[] = new byte[4*1024];
while ((c=is.read(b))!=-1) {
fos.write(b, 0, c);
}
fos.flush();
is.close();
st.close();
con.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
聯(lián)系客服