如何将多个图像直接插入sql数据库?

时间:2015-01-07 09:36:52

标签: c# sql asp.net

我有一个数据库,其中包含产品详细信息产品代码,名称等是列,我在系统中的产品图像在一个文件夹中我需要根据关于的正确行将数据直接添加到数据库产品代码,产品代码和图片均为sam,产品代码如110-1,110-2等,图片名称为110-1jpg,110-2jpg等我有一个程序,但不更新所有行请帮助

DECLARE @CODE varchar

DECLARE image_cursor CURSOR FOR

SELECT CODE FROM MyMast WHERE img IS NULL

OPEN image_cursor;

FETCH NEXT FROM image_cursor

INTO @CODE;

WHILE @@FETCH_STATUS = 0

BEGIN

DECLARE @sql VARCHAR(MAX)

DECLARE @imagePath VARCHAR(255)

SET @imagePath = 'D:\images\' + RTRIM(LTRIM(@CODE)) + '.jpg'

SET @sql = 'UPDATE Mymast'

SET @sql = @sql + 'SET img = (SELECT BulkColumn FROM OPENROWSET( BULK ''' + @imagePath + ''', Single_Blob) AS Picture), SET PictureFileName = ' + @imagepath

SET @sql = @sql + 'WHERE CODE = ''' + @CODE + ''';'

BEGIN TRY

EXECUTE sp_executesql @sql

END TRY

BEGIN CATCH

END CATCH

FETCH NEXT FROM image_cursor

INTO @CODE;

END

CLOSE image_cursor;

DEALLOCATE image_cursor;

SELECT CODE, img FROM MyMast WHERE img IS NOT NULL

1 个答案:

答案 0 :(得分:-1)

DECLARE @CODE int DECLARE image_cursor CURSOR FOR 从MyMast WHERE中选择代码img为NULL OPEN image_cursor; FETCH NEXT FROM image_cursor INTO @CODE; WHILE @@ FETCH_STATUS = 0 开始     DECLARE @sql NVARCHAR(MAX)     DECLARE @imagePath NVARCHAR(255)     SET @imagePath =' D:\ images \' + RTRIM(LTRIM(' 12'))+' .jpg'     SET @sql ='更新MyMast'     SET @sql = @sql +' SET img =(SELECT BulkColumn FROM OPENROWSET(BULK''' + @imagePath +''', Single_Blob)AS img)'     SET @sql = @sql +' WHERE CODE =' + STR(@CODE)

BEGIN TRY
    EXECUTE sp_executesql @sql 
END TRY
BEGIN CATCH

END CATCH   

FETCH NEXT FROM image_cursor 
INTO @CODE;

END 关闭image_cursor; DEALLOCATE image_cursor;

SELECT CODE,img from MyMast WHERE img IS NOT NULL

我试过这段代码,但是在将nvarchar转换为float时出现错误,代码格式为110-1