如何在 Visual Basic .NET 中使用 ADO.NET 读写 BLOB 数据

rockyvan 2008-07-16 08:03:44
创建项目
1. 向您的 SQL Server Northwind 数据库添加一个名为“MyImages”的表。在该表中包含以下字段: • 名称为“ID”,类型为 Int 的标识字段。
• 名称为“Description”,类型为 VarChar,长度为 50 的字段。
• 名称为“ImgField”,类型为 Image 的字段。


2. 启动 Visual Studio .NET,然后新建一个 Visual Basic Windows 应用程序项目。
3. 向默认窗体 Form1 中添加两个 Button 控件。
4. 在“属性”窗口中,将 Button1 的 Text 属性更改为保存到数据库(从文件),然后,将 Button2 的 Text 属性更改为保存到文件(从数据库)。
5. 将下面的代码添加到代码窗口的顶部: Imports System.Data.SqlClient
Imports System.IO


6. 双击 Button1,然后将以下代码添加到 Button1_Click 事件处理程序中:
注意:您必须先将 uid<username> 和 pwd =<strong password> 更改为正确的值,然后才能运行此代码。请确保该用户 ID 具有在数据库中执行此操作所需的适当权限。
Dim con As New SqlConnection _
("Server=YourServer;uid=<username>;pwd=<strong password>;database=northwind")
Dim da As New SqlDataAdapter _
("Select * From MyImages", con)
Dim MyCB As SqlCommandBuilder = New SqlCommandBuilder(da)
Dim ds As New DataSet()

da.MissingSchemaAction = MissingSchemaAction.AddWithKey

Dim fs As New FileStream _
("C:\winnt\Gone Fishing.BMP", FileMode.OpenOrCreate, _
FileAccess.Read)
Dim MyData(fs.Length) As Byte
fs.Read(MyData, 0, fs.Length)
fs.Close()
con.Open()
da.Fill(ds, "MyImages")
Dim myRow As DataRow
myRow = ds.Tables("MyImages").NewRow()

myRow("Description") = "This would be description text"
myRow("imgField") = MyData
ds.Tables("MyImages").Rows.Add(myRow)
da.Update(ds, "MyImages")

fs = Nothing
MyCB = Nothing
ds = Nothing
da = Nothing

con.Close()
con = Nothing
MsgBox ("Image saved to database")


7. 双击 Button2 然后将下列代码添加到 Button2_Click 事件处理程序:
注意:您必须先将 uid<username> 和 pwd =<strong password> 更改为正确的值,然后才能运行此代码。请确保该用户 ID 具有在数据库中执行此操作所需的适当权限。
Dim con As New SqlConnection _
("Server=YourServer;uid=<username>;pwd=<strong password>;database=northwind")
Dim da As New SqlDataAdapter _
("Select * From MyImages", con)
Dim MyCB As SqlCommandBuilder = New SqlCommandBuilder(da)
Dim ds As New DataSet()

con.Open()
da.Fill(ds, "MyImages")
Dim myRow As DataRow
myRow = ds.Tables("MyImages").Rows(0)

Dim MyData() As Byte
MyData = myRow("imgField")
Dim K As Long
K = UBound(MyData)

Dim fs As New FileStream _
("C:\winnt\Gone Fishing2.BMP", FileMode.OpenOrCreate, _
FileAccess.Write)
fs.Write(MyData, 0, K)
fs.Close()

fs = Nothing
MyCB = Nothing
ds = Nothing
da = Nothing

con.Close()
con = Nothing
MsgBox ("Image retrieved")


8. 按 F5 编译并运行该应用程序。
9. 单击“保存到数据库(从文件)”以将图像 C:\WinNT\Gone Fishing.bmp 加载到 SQL Server 中的图像字段。收到确认图像已保存的信息后,请核对您的表进行验证。
10. 单击“保存到文件(从数据库)”以将 SQL Server 图像字段中的数据保存回一个文件中。检查 C:\WinNT\Gone Fishing2.bmp 此时是否存在。
...全文
56 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
rockyvan 2008-07-17
  • 打赏
  • 举报
回复

16,717

社区成员

发帖
与我相关
我的任务
社区描述
VB技术相关讨论,主要为经典vb,即VB6.0
社区管理员
  • VB.NET
  • 水哥阿乐
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧