search
HomeDatabaseMysql TutorialHow to add pictures to mysql

How to add pictures to mysql

Oct 28, 2020 am 09:38 AM
mysql database

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.

How to add pictures to mysql

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How Do I Drop or Modify an Existing View in MySQL?How Do I Drop or Modify an Existing View in MySQL?May 16, 2025 am 12:11 AM

TodropaviewinMySQL,use"DROPVIEWIFEXISTSview_name;"andtomodifyaview,use"CREATEORREPLACEVIEWview_nameASSELECT...".Whendroppingaview,considerdependenciesanduse"SHOWCREATEVIEWview_name;"tounderstanditsstructure.Whenmodifying

MySQL Views: Which design patterns can I use with it?MySQL Views: Which design patterns can I use with it?May 16, 2025 am 12:10 AM

MySQLViewscaneffectivelyutilizedesignpatternslikeAdapter,Decorator,Factory,andObserver.1)AdapterPatternadaptsdatafromdifferenttablesintoaunifiedview.2)DecoratorPatternenhancesdatawithcalculatedfields.3)FactoryPatterncreatesviewsthatproducedifferentda

What Are the Advantages of Using Views in MySQL?What Are the Advantages of Using Views in MySQL?May 16, 2025 am 12:09 AM

ViewsinMySQLarebeneficialforsimplifyingcomplexqueries,enhancingsecurity,ensuringdataconsistency,andoptimizingperformance.1)Theysimplifycomplexqueriesbyencapsulatingthemintoreusableviews.2)Viewsenhancesecuritybycontrollingdataaccess.3)Theyensuredataco

How Can I Create a Simple View in MySQL?How Can I Create a Simple View in MySQL?May 16, 2025 am 12:08 AM

TocreateasimpleviewinMySQL,usetheCREATEVIEWstatement.1)DefinetheviewwithCREATEVIEWview_nameAS.2)SpecifytheSELECTstatementtoretrievedesireddata.3)Usetheviewlikeatableforqueries.Viewssimplifydataaccessandenhancesecurity,butconsiderperformance,updatabil

MySQL Create User Statement: Examples and Common ErrorsMySQL Create User Statement: Examples and Common ErrorsMay 16, 2025 am 12:04 AM

TocreateusersinMySQL,usetheCREATEUSERstatement.1)Foralocaluser:CREATEUSER'localuser'@'localhost'IDENTIFIEDBY'securepassword';2)Foraremoteuser:CREATEUSER'remoteuser'@'%'IDENTIFIEDBY'strongpassword';3)Forauserwithaspecifichost:CREATEUSER'specificuser'@

What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!