将图片转换成二进制存入MySQL数据库中

时间:2021-10-23 21:00:17

package com.zuxia.util;

import java.sql.Connection;
import java.util.ResourceBundle;

import com.alibaba.druid.pool.DruidDataSource;

/**
* 数据库连接池
* @author Administrator
*
*/
public class JDBCUtil {


public static void main(String[] args) throws Exception {
Connection connection = getConnection();
System.out.println(connection);

}

public static Connection getConnection() throws Exception{

//从资源文件中读取
ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc");
String username = resourceBundle.getString("username");
String password = resourceBundle.getString("password");
String url = resourceBundle.getString("url");
String driverClassName = resourceBundle.getString("driverClassName");


DruidDataSource dataSource = new DruidDataSource();

//为数据源设置参数
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setUrl(url);
dataSource.setDriverClassName(driverClassName);

//开启SQL监控
dataSource.setFilters("stat");

return dataSource.getConnection();
}
}

 

/* jdbc.properties*/

username=root
password=123456
url=jdbc:mysql://localhost:3306/db_user
driverClassName=com.mysql.jdbc.Driver

 

 

package com.zuxia.util;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class PictureStore {

public static void pictureStore() {

try {
Connection connection = JDBCUtil.getConnection();
String sql = "insert into tb_user(NAME,picture) values(?,?)";
PreparedStatement prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, "test01");

FileInputStream in = new FileInputStream(new File("E:\\Jellyfish.jpg"));

prepareStatement.setBinaryStream(2, in, in.available());

int executeUpdate = prepareStatement.executeUpdate();

if(executeUpdate > 0){
System.out.println("图片插入成功....");
}

} catch (Exception e) {
e.printStackTrace();
}finally{

//关闭数据库和io流

in.close();

ps.close();

con.close();
}

}
}

 

数据库

CREATE DATABASE db_user
USE db_user

CREATE TABLE tb_user
(
id INT PRIMARY KEY AUTO_INCREMENT,#编号
NAME VARCHAR(20) NOT NULL, #名称
picture BLOB NOT NULL #照片
)ENGINE=INNODB CHARSET=utf8;