During the VB period, binary data is inserted into SQL SERVER through ADODB. STREAM implementation, in.. NET, the operations on the "stream" format are more powerful and simple. This article demonstrates the function of inserting and reading data into SQL SERVER.
Add an OPENFILEDIALOG control on the form, two pictureboxes. The Code is as follows:
Bytes --------------------------------------------------------------------------------------------
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 button#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 ("select image first", 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 ("image inserted successfully", 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
'You can try to remove the comments from the above two sentences to see what the effect is. ^_^
Else
MsgBox ("no image ")
End If
Else
MsgBox ("no data ")
End If
SqlCmd = Nothing
SqlConn. Close ()
SqlConn = Nothing
End Sub
End Class
-----------------------------------------------------------------------------
Database:
----------------
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