use*_*041 5 sql database vb.net prepared-statement
我是vb.net和Microsoft SQL Server 2008中准备好的语句的新手.我找不到任何通过连接字符串连接到数据库并执行预准备语句的好资源.有人可以给我一个例子或指向一个可能有用的资源吗?
这是一些快速示例代码:
Using cn As New SqlConnection("your connection string here"), _
cmd AS New SqlCommand("SELECT * FROM Table WHERE ID= @ID", cn)
cmd.Parameters.Add("@ID", SqlDbType.Int).Value = 12345
cn.Open()
Using rdr As SqlDataREader = cmd.ExecuteReader()
While rdr.Read()
'Do something with the record
End While
rdr.Close()
End Using
End Using
Run Code Online (Sandbox Code Playgroud)
当然,您需要导入System.Data和System.Data.SqlClient.
准备好的语句只不过是包含在事务中的参数化 SqlCommand。
例如,这是一个准备好的语句:
Using c As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
c.Open()
using mytransaction = c.BeginTransaction()
Dim command = New SqlCommand("INSERT INTO yourtable(image) values (@image)", c)
''# this is specific to the FileUploadControl but the idea is to get the
''#image in a byte array; however you do it, it doesn't matter
Dim buffer(FileUpload1.PostedFile.ContentLength) As Byte
FileUpload1.PostedFile.InputStream.Read(buffer, 0, buffer.Length)
command.Parameters.AddWithValue("@image", buffer)
command.ExecuteNonQuery()
mytransaction .Commit()
End Using
End Using
Run Code Online (Sandbox Code Playgroud)