1、新建数据库
CREATE TABLE `photo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL COMMENT '姓名',
`photo` longblob COMMENT '照片',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
2、插入二进制图片数据:
package com.lemon.photo;
//存入图片
import java.sql.*;
import java.io.*;
public class InsertImg
{
public static void main(String args[])
{
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/tbtest";
Connection cn=DriverManager.getConnection(url,"root","123456");
// Statement st=cn.createStatement();
String sql = "insert into photo (id,name,photo) values (null,'测试',?)";
PreparedStatement statement=cn.prepareStatement(sql);
FileInputStream inputStream=new FileInputStream("d://timg.jpg");
statement.setBinaryStream(1,inputStream,inputStream.available());
statement.execute();
inputStream.close();
statement.close();
cn.close();
}catch(Exception e){System.out.println(e.getMessage());}
}
}