java 图片 mysql数据库_通过java向mysql数据库中存取图片

import java.io.*;import java.sql.*;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.Scanner;public classDatabase {//JDBC驱动名

String JDBC_DRIVER = "com.mysql.jdbc.Driver";//数据库URL:这里的tt是数据库名称

String JDBC_URL = "jdbc:mysql://localhost:3306/daImage?useSSL=false&serverTimezone=UTC";//数据库的用户名与密码

String USER = "root";

String PASS= "admin123";//通过DriverManager类获得该连接对象才能访问数据库

Connection connection = null;//通过Connection获得该结果对象用于执行静态的SQL语句//Statement statement = null;

PreparedStatement preparedStatement = null;

String path;

FileInputStream fileInputStream;

Database() {//注册JDBC驱动

try{

Class.forName(JDBC_DRIVER);//数据库的连接:通过DriverManager类的getConnection方法,传入三个参数:数据库URL、用户名、用户密码,实例化connection对象

connection =DriverManager.getConnection(JDBC_URL, USER, PASS);

}catch(ClassNotFoundException e) {

e.printStackTrace();

}catch(SQLException e) {

e.printStackTrace();

}

}public voidadd() {//定义数据库查询语句:查询aa表中的name、sex两列数据

String sql = "insert into taImage values(?,?,?) ";//读取图片,图片放在电脑本地,所以我这里手动复制了路径

File file = new File("/Users/liuliu/Desktop/vv.jpeg");try{

FileInputStream fi= newFileInputStream(file);

preparedStatement=connection.prepareStatement(sql);

preparedStatement.setInt(1, 2);

preparedStatement.setString(2, "图片一");

preparedStatement.setBlob(3, fi);//执行查询语句

int f =preparedStatement.executeUpdate();if (f > 0) {

System.out.println("插入成功");

}else{

System.out.println("插入失败");

}

preparedStatement.close();

connection.close();

}catch(SQLException e) {

e.printStackTrace();

}catch(FileNotFoundException e) {

e.printStackTrace();

}

}public voidselect() {

Blob get_image;

String sql= "select* from taImage";try{//将读取到的图片存放到指定的路径中

FileOutputStream fileOutputStream = new FileOutputStream("/Users/liuliu/Desktop/bb.jpg");

preparedStatement=connection.prepareStatement(sql);

ResultSet resultSet=preparedStatement.executeQuery();while(resultSet.next()) {

get_image= resultSet.getBlob("photo");//将读取到的Blob对象转成字节流

inputStream =get_image.getBinaryStream();inta;byte b[] = new byte[1014];while ((a = inputStream.read(b)) != -1) {

fileOutputStream.write(b,0, a);

}

}

}catch(SQLException e) {

e.printStackTrace();

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值