將圖片存入資料庫【java實現】

來源:互聯網
上載者:User

標籤:資料庫存入圖片   java   

import java.io.FileInputStream;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBCTest {        public static void main(String[] args) throws IOException  {                String driver = "com.mysql.jdbc.Driver";        String url = "jdbc:mysql://127.0.0.1:3306/tuzi?characterEncoding=UTF-8";        String user = "root";        String pass = "";        try        {            Class.forName(driver);    //載入驅動            //串連資料庫            Connection conn = DriverManager.getConnection(url,user,pass);            if(!conn.isClosed())            {                System.out.println("Connection Success!");                //statement 用來執行sql語句                Statement statement = conn.createStatement();                //要執行的sql                String sql = "select * from BST";                //結果集                ResultSet rs = statement.executeQuery(sql);                String tuzi = null;                String luobo = null;                while(rs.next())                {                    tuzi = rs.getString("tuzi");        //tuzi是個int型 主鍵                    luobo = rs.getString("luobo");        //這個是blob 型                System.out.println(tuzi +" " +luobo);                }        /*        這個不行....                FileInputStream fis = new FileInputStream("C:\\6140\\mysql\\src\\tuzi.jpeg");                byte[] rtt = new byte[fis.available()];                fis.read(rtt);                fis.close();        */                        String sqlxx = "insert into BST(tuzi,luobo) values (?,?)";                PreparedStatement pstmt=conn.prepareStatement(sqlxx);                FileInputStream fi=new FileInputStream("C:\\6140\\mysql\\src\\tuzi.jpeg");                pstmt.setInt(1, 521521);                //pstmt.setBinaryStream(2,fi,fi.available());    也行                pstmt.setBlob(2,fi,fi.available());               //也行                pstmt.execute();                         conn.close();            }            }catch(ClassNotFoundException e)        {        } catch (SQLException e) {            e.printStackTrace();        }    }}


將圖片存入資料庫【java實現】

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.