使用SQL語(yǔ)句從電腦導(dǎo)入圖片到數(shù)據(jù)庫(kù)的方法,具體代碼如下所示:
--創(chuàng)建圖片表CREATE TABLE W_PIC( ID INT, --編號(hào) WPATH VARCHAR(80), --完整路徑 PIC VARCHAR(80), --圖片名稱,不帶后綴 img image --圖片內(nèi)容)--圖片表中插入數(shù)據(jù)INSERT INTO W_PIC(ID,WPATH,PIC)SELECT 1, 'C:/Users/w/Desktop/產(chǎn)品圖片/2#加工圖34-C專用.jpg','2#加工圖34-C專用'UNION ALLSELECT 2, 'C:/Users/w/Desktop/產(chǎn)品圖片/129.jpg','129'--創(chuàng)建游標(biāo)DECLARE CUR_PIC CURSOR FOR SELECT ID,WPATH,PIC FROM W_PIC;DECLARE @ID int, @PATH VARCHAR(80), @PIC VARCHAR(80), @STR VARCHAR(100);OPEN CUR_PIC;FETCH NEXT FROM CUR_PIC INTO @ID, @PATH, @PIC;WHILE @@FETCH_STATUS=0BEGIN SET @STR=STR(@ID); --插入圖片數(shù)據(jù) EXECUTE ('UPDATE W_PIC SET img=(SELECT * FROM OPENROWSET(BULK N'''+@PATH+''', SINGLE_BLOB) AS Photo) WHERE ID='+@STR); FETCH NEXT FROM CUR_PIC INTO @ID, @PATH, @PIC;ENDCLOSE CUR_PIC;DEALLOCATE CUR_PIC;知識(shí)點(diǎn)擴(kuò)展:
從MySQL數(shù)據(jù)庫(kù)讀取圖片和向數(shù)據(jù)庫(kù)插入圖片
MySQL數(shù)據(jù)庫(kù)中有一個(gè)數(shù)據(jù)類型為Blob類型,此類型為二進(jìn)制文件類型。下面為從MySQL數(shù)據(jù)庫(kù)讀取圖片和向數(shù)據(jù)庫(kù)插入圖片的代碼,一些的數(shù)據(jù)庫(kù)連接和JDBC代碼就省去了。
package com.an.jdbc.bean; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import org.junit.Test; import com.an.jdbc.utils.JDBCUtils; public class TestBlob { //向數(shù)據(jù)庫(kù)中插入圖片 @Test public void test1() throws Exception{ String sql = "update beauty set photo = ? where id = ?"; Connection connection = JDBCUtils.getConnection(); PreparedStatement ps = connection.prepareStatement(sql); FileInputStream fis = new FileInputStream("C://Users//Administrator//Desktop//1.jpg"); ps.setBlob(1, fis); ps.setInt(2, 2); int update = ps.executeUpdate(); System.out.println(update>0?"success":"failure"); JDBCUtils.closeConnection(null, ps, connection); } //從數(shù)據(jù)庫(kù)中讀取一張圖片 @Test public void test2() throws Exception{ String sql = "select photo from beauty where id=?"; Connection connection = JDBCUtils.getConnection(); PreparedStatement ps = connection.prepareStatement(sql); ps.setInt(1, 2); ResultSet set = ps.executeQuery(); if(set.next()){ InputStream inputStream = set.getBinaryStream(1); FileOutputStream fos = new FileOutputStream("src//copy.jpg"); byte[] b = new byte[1024]; int len = -1; while((len=inputStream.read(b))!=-1){ fos.write(b, 0, len); } fos.close(); inputStream.close(); } JDBCUtils.closeConnection(null, ps, connection); } }總結(jié)
以上所述是小編給大家介紹的使用用SQL語(yǔ)句從電腦導(dǎo)入圖片到數(shù)據(jù)庫(kù)的方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)武林網(wǎng)網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
新聞熱點(diǎn)
疑難解答
圖片精選