How to add pictures to mysql
Method to add pictures to mysql: First, set the field type of the database to store pictures as a blob binary large object type; then convert the picture stream into binary; and finally insert the picture into the database.
Recommendation: "mysql video tutorial"
Normal image storage or put it into the local disk, Or save it in the database. Saving it locally is very simple. Now I will write down here how to save the picture into the mysql database
If you want to save the picture into the database, you need to convert the picture into binary.
1. The field type for storing pictures in the database must be blob binary large object type
2. Convert the picture stream into binary
Put the code example below
1. Database
CREATE TABLE `photo` ( `id` int(11) NOT NULL, `name` varchar(255) DEFAULT NULL, `photo` blob, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2. Database link
/** * */ package JdbcImgTest; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * @author Administrator * */ public class DBUtil { // 定义数据库连接参数 public static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver"; public static final String URL = "jdbc:mysql://localhost:3306/test"; public static final String USERNAME = "root"; public static final String PASSWORD = "root"; // 注册数据库驱动 static { try { Class.forName(DRIVER_CLASS_NAME); } catch (ClassNotFoundException e) { System.out.println("注册失败!"); e.printStackTrace(); } } // 获取连接 public static Connection getConn() throws SQLException { return DriverManager.getConnection(URL, USERNAME, PASSWORD); } // 关闭连接 public static void closeConn(Connection conn) { if (null != conn) { try { conn.close(); } catch (SQLException e) { System.out.println("关闭连接失败!"); e.printStackTrace(); } } } //测试 /* public static void main(String[] args) throws SQLException { System.out.println(DBUtil.getConn()); } */ }
3. Picture stream
package JdbcImgTest; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * @author Administrator * */ public class ImageUtil { // 读取本地图片获取输入流 public static FileInputStream readImage(String path) throws IOException { return new FileInputStream(new File(path)); } // 读取表中图片获取输出流 public static void readBin2Image(InputStream in, String targetPath) { File file = new File(targetPath); String path = targetPath.substring(0, targetPath.lastIndexOf("/")); if (!file.exists()) { new File(path).mkdir(); } FileOutputStream fos = null; try { fos = new FileOutputStream(file); int len = 0; byte[] buf = new byte[1024]; while ((len = in.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (null != fos) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
4. Transcoding storage
package JdbcImgTest; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * @author Administrator 测试写入数据库以及从数据库中读取 */ public class ImageDemo { // 将图片插入数据库 public static void readImage2DB() { String path = "D:/Eclipse/eclipseWorkspace/TestProject/Img/mogen.jpg"; Connection conn = null; PreparedStatement ps = null; FileInputStream in = null; try { in = ImageUtil.readImage(path); conn = DBUtil.getConn(); String sql = "insert into photo (id,name,photo)values(?,?,?)"; ps = conn.prepareStatement(sql); ps.setInt(1, 1); ps.setString(2, "Tom"); ps.setBinaryStream(3, in, in.available()); int count = ps.executeUpdate(); if (count > 0) { System.out.println("插入成功!"); } else { System.out.println("插入失败!"); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtil.closeConn(conn); if (null != ps) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } } // 读取数据库中图片 public static void readDB2Image() { String targetPath = "C:/Users/Jia/Desktop/mogen.jpg"; Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = DBUtil.getConn(); String sql = "select * from photo where id =?"; ps = conn.prepareStatement(sql); ps.setInt(1, 1); rs = ps.executeQuery(); while (rs.next()) { InputStream in = rs.getBinaryStream("photo"); ImageUtil.readBin2Image(in, targetPath); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtil.closeConn(conn); if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } } } //测试 public static void main(String[] args) { //readImage2DB(); readDB2Image(); } }
The above is the detailed content of How to add pictures to mysql. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP development practice: Use PHPMailer to send emails to users in the MySQL database Introduction: In the construction of the modern Internet, email is an important communication tool. Whether it is user registration, password reset, or order confirmation in e-commerce, sending emails is an essential function. This article will introduce how to use PHPMailer to send emails and save the email information to the user information table in the MySQL database. 1. Install the PHPMailer library PHPMailer is

As the amount of data continues to increase, database performance has become an increasingly important issue. Hot and cold data separation processing is an effective solution that can separate hot data and cold data, thereby improving system performance and efficiency. This article will introduce how to use Go language and MySQL database to separate hot and cold data. 1. What is hot and cold data separation processing? Hot and cold data separation processing is a way of classifying hot data and cold data. Hot data refers to data with high access frequency and high performance requirements. Cold data

To what extent can I develop MySQL database skills to be successfully employed? With the rapid development of the information age, database management systems have become an indispensable and important component in all walks of life. As a commonly used relational database management system, MySQL has a wide range of application fields and employment opportunities. So, to what extent do MySQL database skills need to be developed to be successfully employed? First of all, mastering the basic principles and basic knowledge of MySQL is the most basic requirement. MySQL is an open source relational database management

As the amount of data increases, database backup becomes more and more important. For the MySQL database, we can use the Go language to achieve automated incremental backup. This article will briefly introduce how to use Go language to perform incremental backup of MySQL database data. 1. Install the Go language environment. First, we need to install the Go language environment locally. You can go to the official website to download the corresponding installation package and install it. 2. Install the corresponding library. The Go language provides many third-party libraries for accessing MySQL databases, among which the most commonly used ones are

How to use MySQL database for time series analysis? Time series data refers to a collection of data arranged in time order, which has temporal continuity and correlation. Time series analysis is an important data analysis method that can be used to predict future trends, discover cyclical changes, detect outliers, etc. In this article, we will introduce how to use a MySQL database for time series analysis, along with code examples. Create a data table First, we need to create a data table to store time series data. Suppose we want to analyze the number

How to use MySQL database for image processing? MySQL is a powerful relational database management system. In addition to storing and managing data, it can also be used for image processing. This article will introduce how to use a MySQL database for image processing and provide some code examples. Before you begin, make sure you have installed a MySQL database and are familiar with basic SQL statements. Create a database table First, create a new database table to store the image data. The structure of the table can be as follows

With the large amount of data that needs to be stored and processed, MySQL has become one of the most commonly used relational databases in application development. The Go language is becoming more and more popular among developers due to its efficient concurrency processing and concise syntax. This article will lead readers to implement reliable MySQL database connection through Go language, allowing developers to query and store data more efficiently. 1. Several ways for Go language to connect to MySQL database. There are usually three ways to connect to MySQL database in Go language, which are: 1. Third-party library

In recent years, the Go language has become increasingly popular among developers and has become one of the preferred languages for developing high-performance web applications. MySQL is also a popular database that is widely used. In the process of combining these two technologies, caching is a very important part. The following will introduce how to use Go language to handle the cache of MySQL database. The concept of caching In web applications, caching is a middle layer created to speed up data access. It is mainly used to store frequently requested data to
