Using statement with a scalar query

1.6k views Asked by At

Can you show a coding example that has the "Using" statement with a scalar query?

I could not find any sample coding for this by searching yet.

1

There are 1 answers

1
Steven Doggart On BEST ANSWER

Here's the example from the MSDN page on the ExecuteScalar method:

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

Heres the link:

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