我创建了一个新的SQL Server本地数据库,其中包含一个名为drink
的表。
我使用Microsoft Visual Studio 2008。
在表格中我定义了以下列:
id [int], kind [varchar], year [datatime], image [image]
我想将图片插入image
栏,但我不知道该怎么做。
我需要这个专栏,因为我想使用VB.NET在DataGridView中显示所有数据
感谢您的帮助!
答案 0 :(得分:3)
使用openrowset可以将图像插入数据库:
insert into tableName (id,kind,ImageColumn)
SELECT 1,'JPEG',BulkColumn
FROM Openrowset( Bulk '<Path of the image>', Single_Blob) as img
答案 1 :(得分:1)
这对我有用......
Imports System.Data.Sql
Imports System.IO
Imports System.drawing
Module Module1
Private Const _ConnectString As String = "your connection string here"
Sub Main()
Dim MyImage As Image = Image.FromFile("RandomImage.jpg")
Dim Id As Long = 1
SaveDrinkImage(MyImage, Id)
End Sub
Sub SaveDrinkImage(MyImage As Image, Id As Long)
Dim ImageBytes(0) As Byte
Using mStream As New MemoryStream()
MyImage.Save(mStream, MyImage.RawFormat)
ImageBytes = mStream.ToArray()
End Using
Dim adoConnect = New SqlClient.SqlConnection(_ConnectString)
Dim adoCommand = New SqlClient.SqlCommand("UPDATE [drink] SET [image]=@MyNewImage WHERE [id]=@id", adoConnect)
With adoCommand.Parameters.Add("@MyNewImage", SqlDbType.Image)
.Value = ImageBytes
.Size = ImageBytes.Length
End With
With adoCommand.Parameters.Add("@id", SqlDbType.BigInt)
.Value = Id
End With
adoConnect.Open()
adoCommand.ExecuteNonQuery()
adoConnect.close()
End Sub
End Module
答案 2 :(得分:0)
有两种方法。您可以将图像存储为数据库中的blob,也可以将路径(字符串)存储到图像文件中。有一个答案可以讨论这个问题:Storing images in SQL Server?
答案 3 :(得分:0)
试试这个:
Sub SaveDrinkToDB(name As String, imageFilePath As String)
Using cn = New SqlConnection("connection string here")
cn.Open()
Using cmd = New SqlCommand("INSERT INTO Drink (Name, Image) Values(@Name,@Image)", cn)
cmd.Parameters.AddWithValue("@name", name)
cmd.Parameters.AddWithValue("@Image", File.ReadAllBytes(imageFilePath))
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
用法:
SaveDrinkToDB("Milk", "c:\drink.png")
答案 4 :(得分:0)
USE [database_name]
GO
INSERT INTO [schema].[tablename]([property1],[property2],[Property3],[Image])
VALUES
('value','value','value','C:\pathname.jpg')
GO