怎样把图片存上mysql数据库表中_把图片存到mysql数据库中

在百度bae的使用过程中发现文件丢失问题,百度文档是这样说明的

4fCsl6etrsJXwAAAAASUVORK5CYII=

我就想着能不能把数据存到数据库中

网上看到了

package com.bai;

import java.sql.*;

import java.io.*;

/**

author@tongxiao

time:2007.09.14

*/

public class TestImage {

private static final String URL = "jdbc:mysql://localhost/Image?user=root&password=baipeng&useUnicode=true";

private Connection conn = null;

private PreparedStatement pstmt = null;//容器 放sql语句的

private ResultSet rs = null;

private File file = null;

private InputStream inputImage = null;

private OutputStream outputImage = null;

public void blobInsert(String infile) {

try {

Class.forName("com.mysql.jdbc.Driver");

System.out.println("Driver loaded!");

conn = DriverManager.getConnection(URL);

System.out.println("Database connected!");//建立连接

pstmt = conn.prepareStatement("insert into Country (name,flag,description) values (?,?,?)");

pstmt.setString(1, "china");//命名name为china

file = new File(infile);

try {

inputImage = new FileInputStream(file);

} catch (FileNotFoundException e) {

e.printStackTrace();

}

pstmt.setBinaryStream(2, inputImage, (int) (file.length()));

pstmt.setString(3, "A flag of China");

pstmt.executeUpdate();

System.out.println("commit successfully");

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

} finally {

try {

inputImage.close();

pstmt.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

//上面是存的过程 下面是读的过程

public void readBolb(String path, int id) {

InputStream is = null;

byte[] buffer = new byte[4096];

try {

Class.forName("com.mysql.jdbc.Driver");

System.out.println("Driver loaded!");

conn = DriverManager.getConnection(URL);

System.out.println("Database connected!");

pstmt = conn.prepareStatement("select flag from Country where id =?");

System.out.println("select ok");

pstmt.setInt(1, id);

rs = pstmt.executeQuery();

rs.next();

file = new File(path);

if (!file.exists()) {

try {

file.createNewFile();

} catch (IOException e) {

e.printStackTrace();

}

}

try {

outputImage = new FileOutputStream(file);

System.out.println(outputImage.toString());

} catch (FileNotFoundException e) {

e.printStackTrace();

}

Blob blob = rs.getBlob("flag");

is = blob.getBinaryStream();

try {

System.out.println(is.available());

} catch (IOException e2) {

e2.printStackTrace();

}

try {

System.out.println(is.available());

} catch (IOException e1) {

e1.printStackTrace();

}

int size = 0;

try {

while ((size = is.read(buffer)) != -1) {

System.out.println(size);

outputImage.write(buffer, 0, size);

}

} catch (IOException e) {

e.printStackTrace();

}

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (SQLException e) {

e.printStackTrace();

} finally {

try {

is.close();

outputImage.close();

pstmt.close();

conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

public static void main(String[] args) {

new TestImage().blobInsert("c:\\Users\\peng\\Pictures\\1.jpg");

new TestImage().readBolb("c:\\Users\\peng\\Pictures\\mysqlreadimage\\2.jpg", 1);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
图片保存MySQL数据库,可以采用以下步骤: 1. 将图片转换成二进制数据。 2. 创建一个BLOB类型的字段来存储二进制数据。 3. 使用INSERT语句将二进制数据插入到BLOB字段。 以下是一个示例代码: ```python import mysql.connector from mysql.connector import Error def convertToBinaryData(filename): # 将图片转换成二进制数据 with open(filename, 'rb') as file: binaryData = file.read() return binaryData def insertBLOB(emp_id, name, photo): try: connection = mysql.connector.connect(host='localhost', database='test', user='root', password='password') cursor = connection.cursor() sql_insert_blob_query = """ INSERT INTO employees (id, name, photo) VALUES (%s,%s,%s)""" empPicture = convertToBinaryData(photo) # 插入二进制数据到BLOB字段 insert_blob_tuple = (emp_id, name, empPicture) result = cursor.execute(sql_insert_blob_query, insert_blob_tuple) connection.commit() print("Image and file inserted successfully as a BLOB into employees table", result) except mysql.connector.Error as error: print("Failed inserting BLOB data into MySQL table {}".format(error)) finally: # 关闭数据库连接 if (connection.is_connected()): cursor.close() connection.close() print("MySQL connection is closed") # 调用 insertBLOB 函数插入二进制数据到BLOB字段 insertBLOB(1, "John", "/path/to/image.jpg") ``` 请注意,此示例仅供参考,并且可能需要根据您的数据库架构和需求进行更改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值