我们知道可以把二进制数据存进数据库里去,可是没做过哦!
前两天一网友问题怎么做?才去查一下资料,试验了一下
//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 数据库用 "CREATE TABLE mytable(id autoincrement, picname varchar(50), pic BLOB);" 建表
st.close();
con.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
// SavePic.java 将图片保存至数据库
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 从数据库中读出图片存成文件
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();
}
}
}