VB.NET中的准备语句

时间:2011-09-08 16:05:31

标签: sql database vb.net prepared-statement

我是vb.net和Microsoft SQL Server 2008中准备好的语句的新手。我找不到任何通过连接字符串连接到数据库并执行预准备语句的好资源。有人可以给我一个例子或者指出一个可能有用的资源吗?

2 个答案:

答案 0 :(得分:7)

以下是一些快速示例代码:

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

当然,您需要导入System.Data和System.Data.SqlClient。

答案 1 :(得分:4)

预备语句只是封装在事务中的参数化Sql命令。

例如,这是一份准备好的声明:

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