如何将图片存入MySQL中的blob去

建立表:

CREATE TABLE example (name VARCHAR(100),city VARCHAR(100),image BLOB,Phone VARCHAR(100));


使用一张图片qqq.jpg

存图片的代码:

package test;

import java.sql.*;
import java.io.*;

public class SaveImageToDatabase {
	public static void main(String[] args) throws SQLException {
		// declare a connection by using Connection interface
		Connection connection = null;
		/*
		 * Create string of connection url within specified format with machine
		 * name, port number and database name. Here machine name id localhost
		 * and database name is mahendra.
		 */
		String connectionURL = "jdbc:mysql://localhost:3306/test";
		/*
		 * declare a resultSet that works as a table resulted by execute a
		 * specified sql query.
		 */
		ResultSet rs = null;
		// Declare prepare statement.
		PreparedStatement psmnt = null;
		// declare FileInputStream object to store binary stream of given image.
		FileInputStream fis;
		try {
			// Load JDBC driver "com.mysql.jdbc.Driver"
			Class.forName("com.mysql.jdbc.Driver").newInstance();

			/*
			 * Create a connection by using getConnection() method that takes
			 * parameters of string type connection url, user name and password
			 * to connect to database.
			 */
			connection = DriverManager.getConnection(connectionURL, "root",
					"root");
			// create a file object for image by specifying full path of image
			// as parameter.
			File image = new File("D:/qqq.jpg");
			/*
			 * prepareStatement() is used for create statement object that is
			 * used for sending sql statements to the specified database.
			 */
			psmnt = connection
					.prepareStatement("insert into example(name, city, image, Phone) "
							+ "values(?,?,?,?)");
			psmnt.setString(1, "michael");
			psmnt.setString(2, "Delhi");
			psmnt.setString(4, "123456");
			fis = new FileInputStream(image);
			psmnt.setBinaryStream(3, (InputStream) fis, (int) (image.length()));
			/*
			 * executeUpdate() method execute specified sql query. Here this
			 * query insert data and image from specified address.
			 */
			int s = psmnt.executeUpdate();
			if (s > 0) {
				System.out.println("Uploaded successfully !");
			} else {
				System.out.println("unsucessfull to upload image.");
			}
		}

		// catch if found any exception during rum time.
		catch (Exception ex) {
			System.out.println("Found some error : " + ex);
		} finally {
			// close all the connections.
			connection.close();
			psmnt.close();
		}
	}
}



将图片从数据库中取出来,放到文件中:

package com.liang.java;




import java.sql.*;
import java.io.*;


public class GetImageFromDatabase {
	public static void main(String[] args) throws SQLException {
		Connection connection = null;
		String connectionURL = "jdbc:mysql://localhost:3308/thzdatabase";
		ResultSet rs = null;
		PreparedStatement psmnt = null;
		// declare FileInputStream object to store binary stream of given image.
		FileOutputStream fos;
		try {
			File imageout = new File("D:/1111.png");
			fos=new FileOutputStream(imageout);
			
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			connection = DriverManager.getConnection(connectionURL, "root",
					"111111");
			psmnt = connection
					.prepareStatement("select image from test where name=? ");
			psmnt.setString(1, "michael");
			rs=psmnt.executeQuery();
			rs.next();
			Blob image_blob=rs.getBlob("image");
			InputStream is=image_blob.getBinaryStream();
			
			byte[] b = null;
			byte [] a = new byte[is.read(b, 0, b.length)];
			
			
			System.out.println(is.toString());
			
			 int ch = 0;  
			    try {  
			        while((ch=is.read()) != -1){  
			            fos.write(ch);  
			        }  
			    } catch (IOException e1) {  
			        e1.printStackTrace();  
			    } finally{  
			                 
			        fos.close();  
			        is.close();  
			    }
		}
		// catch if found any exception during rum time.
		catch (Exception ex) {
			System.out.println("Found some error : " + ex);
		} finally {
			// close all the connections.
			System.out.println("Found success!");
			connection.close();
			psmnt.close();
		}
	}
}


  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
图片存到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") ``` 请注意,此示例仅供参考,并且可能需要根据您的数据库架构和需求进行更改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值