1.创建数据表
CREATE TABLE `tb_context` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`context` longtext,
`picture` longblob,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
2.读写操作
package com.JDBC;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class testLongBlobPicture {
String url ="jdbc:mysql://localhost:3306/test";
String driver="com.mysql.jdbc.Driver";
String user = "root";
String password = "root";
Connection conn=null;
PreparedStatement ps=null;
ResultSet resultSet=null;
public void connectionDB(){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
System.out.println("Successfully connected");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void WriteContextIntoDB(){
try {
//1.将大二进制文件插入到数据库
String insertsql="insert into tb_context(picture) value(?)";
ps = conn.prepareStatement(insertsql);
File file = new File("E:\\1.jpg");
FileInputStream fileInputStream = new FileInputStream(file);
ps.setBinaryStream(1, fileInputStream,
(int)fileInputStream.available());
ps.executeUpdate();
System.out.println("成功向数据库插入图片 ");
} catch (SQLException e) {
System.out.println("SQLException");
e.printStackTrace();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException ");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//2.从数据读出二进制图片并写到磁盘
public void ReadContextFromDB(){
try {
String sql = "select*from tb_context where id=?";
ps = conn.prepareStatement(sql);
ps.setInt(1,6);
ps.executeQuery();
resultSet = ps.getResultSet();
if (resultSet.next()) {
InputStream inputStream = resultSet.getBinaryStream("picture");
FileOutputStream fileOutputStream = new FileOutputStream(new File(
"E:\\InputPicture.jpg"));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
inputStream.close();
fileOutputStream.close();
}
} catch (SQLException e) {
System.out.println("SQLException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
testLongBlobPicture t = new testLongBlobPicture();
t.connectionDB();
t.WriteContextIntoDB();
t.ReadContextFromDB();
System.out.println("读取成功,请到E盘查看");
}
}