使用sql语句从电脑导入图片到数据库的方法,具体代码如下所示:
--创建图片表
create table w_pic
(
id int, --编号
wpath varchar(80), --完整路径
pic varchar(80), --图片名称,不带后缀
img image --图片内容
)
--图片表中插入数据
insert into w_pic(id,wpath,pic)
select 1, 'c:\users\w\desktop\产品图片#加工图34-c专用.jpg','2#加工图34-c专用'
union all
select 2, 'c:\users\w\desktop\产品图片9.jpg','129'
--创建游标
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=0
begin
set @str=str(@id);
--插入图片数据
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;
end
close cur_pic;
deallocate cur_pic;
知识点扩展:
从mysql数据库读取图片和向数据库插入图片
mysql数据库中有一个数据类型为blob类型,此类型为二进制文件类型。下面为从mysql数据库读取图片和向数据库插入图片的代码,一些的数据库连接和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 {
//向数据库中插入图片
@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\.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);
}
//从数据库中读取一张图片
@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);
}
}
总结
以上所述是www.887551.com给大家介绍的使用用sql语句从电脑导入图片到数据库的方法,希望对大家有所帮助