1

Looking for the simplest way to get a single value from a database. This gets confusing when you consider all of the 9,000 ways that exist to do this in a .NET language. SqlCommands, DataReaders, Recordsets... oh my!

Assume I already have a connection to the DB opened. I simply want to do something like this:

Dim age As Integer = <SQL statement here>

2 Answers 2

6
SqlConnection conn = new SqlConnection("connection string goes here");
SqlCommand cmd = new SqlCommand("SELECT foo FROM ...", conn);

conn.Open();
int age = (int)cmd.ExecuteScalar();
conn.Close();

Not a VB.Net guy, but I think it would look something like this in VB.Net:

Dim conn As SqlConnection = new SqlConnection("connection string goes here")
Dim cmd As SqlCommand = new SqlCommand("SELECT foo FROM ...", conn);

conn.Open()
Dim age As Integer = Convert.ToInt32(cmd.ExecuteScalar())
conn.Close()
Sign up to request clarification or add additional context in comments.

1 Comment

HAHA! It's hard for a C# guy not too use semi-colons! :D
4

Try something like this:

Dim age As Integer=0
Using conn As New SqlClient.SqlConnection("YourConnectionString") 
    Using cmd As SqlClient.SqlCommand = conn.CreateCommand() 

        cmd.CommandText = "SELECT Age FROM Customer WHERE CustomerNumber = @CustNum" 
        cmd.Parameters.AddWithValue("@CustNum", SomeCustomerNumber) 
        conn.Open() 
        age = Convert.ToInt32(cmd.ExecuteScalar().ToString()) 

      End Using 
End Using 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.