Java JDBC将图片以二进制形式保存到MySQL数据库并从MySQL数据库中读取图片到本地
数据库表结构:
CREATE TABLE `t_image` (
`id` int NOT NULL AUTO_INCREMENT,
`image` longblob NULL,
PRIMARY KEY (`id`) USING BTREE
)
JDBC对数据库操作:
public class ImageStoreTest {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test2?characterEncoding=utf-8&useSSL=false";
String username = "root";
String password = "";
Connection con = DriverManager.getConnection(url, username, password);
String sql = "insert into t_image(image) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
FileInputStream fi = new FileInputStream("src\\main\\java\\com\\test\\pub1\\tree.jpg");
pstmt.setBinaryStream(1, fi, fi.available());
pstmt.execute();
String sql2 = "select image from t_image";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql2);
rs.next();
Blob blob = rs.getBlob(1);
FileOutputStream fo = new FileOutputStream("src\\main\\java\\com\\test\\pub2\\treeRead.jpg");
fo.write(blob.getBytes(1, (int)blob.length()));
st.close();
pstmt.close();
fi.close();
fo.close();
con.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}