700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > java 向 mysql数据库存储图片_基于java向mysql数据库中存取图片

java 向 mysql数据库存储图片_基于java向mysql数据库中存取图片

时间:2024-08-01 23:58:28

相关推荐

java 向 mysql数据库存储图片_基于java向mysql数据库中存取图片

import java.io.*;

import java.sql.*;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.Scanner;

public class Database {

//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 void add() {

// 定义数据库查询语句:查询aa表中的name、sex两列数据

String sql = "insert into taImage values(?,?,?) ";

// 读取图片,图片放在电脑本地,所以我这里手动复制了路径

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

try {

FileInputStream fi = new FileInputStream(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 void select() {

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();

int a;

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();

}

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。