在VB時期, 向SQL SERVER 中插入位元據, 是通過 ADODB.STREAM 實現, 在.NET中, 對 “流”格式的操作更加強大而簡單,本篇示範向SQL SERVER 中插入資料並讀出的功能.
在表單上添加一個 OPENFILEDIALOG 控制項, 兩個PICTUREBOX, 代碼如下:
--------------------------------------------------------------------------------------------
Imports System.IO
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
Me.Dispose(True)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ofdPic.ShowDialog = DialogResult.OK Then
pbPreview.Image = Image.FromFile(ofdPic.FileName)
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If pbPreview.Image Is Nothing Then
MsgBox("請先選擇圖片", MsgBoxStyle.Exclamation)
Exit Sub
End If
Dim fs As FileStream = New FileStream(ofdPic.FileName, FileMode.Open, FileAccess.Read)
Dim bt(fs.Length) As Byte
fs.Read(bt, 0, fs.Length)
fs.Close()
fs = Nothing
Dim sqlConn As SqlClient.SqlConnection = New SqlClient.SqlConnection("Server=(local);User Id=sa;Password=123;Database=pubs")
sqlConn.Open()
Dim sqlCmd As New SqlClient.SqlCommand("sp_InsertImage", sqlConn)
sqlCmd.CommandType = CommandType.StoredProcedure
sqlCmd.Parameters.Add("@img", SqlDbType.Image).Value = bt
sqlCmd.ExecuteNonQuery()
sqlCmd = Nothing
sqlConn.Close()
sqlConn = Nothing
MsgBox("圖片插入成功", MsgBoxStyle.Information)
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim sqlConn As SqlClient.SqlConnection = New SqlClient.SqlConnection("Server=(local);User Id=sa;Password=123;Database=pubs")
sqlConn.Open()
Dim sqlCmd As New SqlClient.SqlCommand("SELECT img FROM test WHERE t_ID=3", sqlConn)
sqlCmd.CommandType = CommandType.Text
Dim bt() As Byte = sqlCmd.ExecuteScalar()
If Not bt Is Nothing Then
If bt.Length > 0 Then
Dim fs As MemoryStream = New MemoryStream(bt)
pbReview.Image = Image.FromStream(fs)
'fs.Close
'fs = Nothing
'可以自己試著將上面兩句的注釋去掉, 看有什麼效果 ^_^
Else
MsgBox("無圖片")
End If
Else
MsgBox("無資料")
End If
sqlCmd = Nothing
sqlConn.Close()
sqlConn = Nothing
End Sub
End Class
-----------------------------------------------------------------------------
資料庫部分:
----------------
use pubs
go
Create Table test(t_ID int identity(1,1), img image)
go
Create Procedure sp_InsertImage
@img image
AS
Insert Into test (img) Values (@img)
go