使用带有标量查询的语句

时间:2012-05-30 22:19:45

标签: vb.net using using-statement scalar executescalar

你能展示一个带有标量查询的“Using”语句的编码示例吗?

我通过搜索找不到任何样本编码。

1 个答案:

答案 0 :(得分:3)

以下是ExecuteScalar方法的MSDN页面中的示例:

Public Function AddProductCategory(ByVal newName As String, ByVal connString As String) As Integer
    Dim newProdID As Int32 = 0
    Dim sql As String = _
     "INSERT INTO Production.ProductCategory (Name) VALUES (@Name); SELECT CAST(scope_identity() AS int);"

    Using conn As New SqlConnection(connString)
        Dim cmd As New SqlCommand(sql, conn)
        cmd.Parameters.Add("@Name", SqlDbType.VarChar)
        cmd.Parameters("@Name").Value = newName
        Try
            conn.Open()
            newProdID = Convert.ToInt32(cmd.ExecuteScalar())
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Using

    Return newProdID
End Function

继承人的链接:

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx#Y374