溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何在MySQL中存儲圖片

發(fā)布時間:2021-05-20 16:57:17 來源:億速云 閱讀:3947 作者:Leah 欄目:MySQL數(shù)據(jù)庫

如何在MySQL中存儲圖片?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

首先,先要在數(shù)據(jù)庫中建表。我在名為test的數(shù)據(jù)庫下建立了一個叫pic的表。該表包括3列,idpic, caption和img。其中idpic是主鍵,caption是對圖片的表述,img是圖像文件本身。建表的SQL語句如下:

DROP TABLE IF EXISTS `test`.`pic`;
CREATE TABLE `test`.`pic` (
 `idpic` int(11) NOT NULL auto_increment,
 `caption` varchar(45) NOT NULL default '',
 `img` longblob NOT NULL,
 PRIMARY KEY (`idpic`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

將上面的語句輸入到命令行中(如果安裝了Query Brower, 你可以按照參考[1]中的指示來建表,那樣會更加方便。),執(zhí)行,表建立成功。

3 實現(xiàn)圖像存儲類

表完成后,我們就開始寫個Java類,來完成向數(shù)據(jù)庫中插入圖片的操作。我們知道,Java與數(shù)據(jù)庫連接是通過JDBC driver來實現(xiàn)的。我用的是MySQL網(wǎng)站上提供的MySQL Connector/J,如果你用的是其他類型的driver, 在下面的實現(xiàn)過程中可能會有些許差別。

3.1 裝載JDBC驅(qū)動,建立連接

JDK中提供的DriverManager接口用來管理Java Application 和 JDBC Driver之間的連接。在使用這個接口之前, DriverManager需要知道要連接的JDBC 驅(qū)動。最簡單的方法就是用Class.forName()來向DriverManager注冊實現(xiàn)了java.sql.Driver 的接口類。對MySQL Connector/J來說,這個類的名字叫com.mysql.jdbc.Driver。

下面這個簡單的示例說明了怎樣來注冊Connector/J Driver。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class LoadDriver {
  public static void main(String[] args) {
    try {
      // The newInstance() call is a work around for some
      // broken Java implementations
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      
      // Connection con = DriverManager.getConnection(……)
      // ……
    } catch (Exception ex) {
      // handle the error
    }
}

向DriverManager注冊了驅(qū)動后,我們就可以通過調(diào)用 DriverManager.getConnection()方法來獲得和數(shù)據(jù)庫的連接。其實在上面的例子中就有這條語句,只不過被注釋掉了。在后面的實現(xiàn)中會有完整的例子。

3.2 PreparedStatement

完成上面的步驟后,我們就可以同過建立的連接創(chuàng)建Statement接口類,來執(zhí)行一些SQL語句了。在下面的例子,我用的是PreparedStatement,還有CallableStatement,它可以執(zhí)行一些存儲過程和函數(shù),這里不多講了。下面的代碼片斷是向pic表中插入一條記錄。其中(1)處Connection接口的對象con通過調(diào)用prepareStatement 方法得到預(yù)編譯的SQL 語句(precompiled SQL statement);(2)處是為該insert語句的第一個問號賦值,(3)為第二個賦值,(4)為第三個,這步也是最該一提的,用的方法是setBinaryStream(),第一個參數(shù)3是指第三個問號,fis是一個二進(jìn)制文件流,第三個參數(shù)是該文件流的長度。

PreparedStatement ps;
…
ps = con.prepareStatement("insert into PIC values (?,?,?)"); // (1)
ps.setInt(1, id); //(2)
ps.setString(2, file.getName()); (3)
ps.setBinaryStream(3, fis, (int)file.length()); (4)
ps.executeUpdate();
…

3.3 完整代碼

上面列出了完整的代碼。

package com.forrest.storepic;
 import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
/**
 * This class describes how to store picture file into MySQL.
 * @author Yanjiang Qian
 * @version 1.0 Jan-02-2006
 */
public class StorePictures {
  
  private String dbDriver;
  private String dbURL;
  private String dbUser;
  private String dbPassword;
  private Connection con;
  private PreparedStatement ps; 
 
  public StorePictures() {
    dbDriver = "com.mysql.jdbc.Driver";
    dbURL = "jdbc:mysql://localhost:3306/test";
    dbUser = "root";
    dbPassword = "admin";
    initDB();
  }
  
  public StorePictures(String strDriver, String strURL,
      String strUser, String strPwd) {
    dbDriver = strDriver;
    dbURL = strURL;
    dbUser = strUser;
    dbPassword = strPwd;
    initDB();
  }
 
  public void initDB() {
    try {
      // Load Driver
      Class.forName(dbDriver).newInstance();
      // Get connection
      con = DriverManager.getConnection(dbURL,
          dbUser, dbPassword);      
    } catch(ClassNotFoundException e) {
      System.out.println(e.getMessage());
    } catch(SQLException ex) {
      // handle any errors
      System.out.println("SQLException: " + ex.getMessage());
      System.out.println("SQLState: " + ex.getSQLState());
      System.out.println("VendorError: " + ex.getErrorCode());
 
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
 
  public boolean storeImg(String strFile) throws Exception {
    boolean written = false;
    if (con == null)
      written = false;
    else {
      int id = 0;
      File file = new File(strFile);
      FileInputStream fis = new FileInputStream(file);
      
      try {       
        ps = con.prepareStatement("SELECT MAX(idpic) FROM PIC");
        ResultSet rs = ps.executeQuery();
        
        if(rs != null) {
          while(rs.next()) {
            id = rs.getInt(1)+1;
          }
        } else {    
          return written;
        }
        
        ps = con.prepareStatement("insert "
            + "into PIC values (?,?,?)");
        ps.setInt(1, id);
        ps.setString(2, file.getName());
        ps.setBinaryStream(3, fis, (int) file.length());
        ps.executeUpdate();
        
        written = true;
      } catch (SQLException e) {
        written = false;
        System.out.println("SQLException: "
            + e.getMessage());
        System.out.println("SQLState: "
            + e.getSQLState());
        System.out.println("VendorError: "
            + e.getErrorCode());
        e.printStackTrace();
      } finally {       
        ps.close();
        fis.close();
        // close db con
        con.close();
      }
    }
    return written;
  }
  
  /**
   * Start point of the program
   * @param args CMD line
   */
  public static void main(String[] args) {
    if(args.length != 1) {
      System.err.println("java StorePictures filename");
      System.exit(1);
    }
    boolean flag = false;
    StorePictures sp = new StorePictures();
    try {
      flag = sp.storeImg(args[0]);
    } catch (Exception e) {
      e.printStackTrace();
    }
    if(flag) {
      System.out.println("Picture uploading is successful.");
    } else {
      System.out.println("Picture uploading is failed.");
    }
  }
}

看完上述內(nèi)容,你們掌握如何在MySQL中存儲圖片的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI