2011-10-27 244 views
1

尋找從數據庫獲取單個值的最簡單方法。當你考慮使用.NET語言編寫的所有9,000種方法時,這會讓你感到困惑。 SqlCommands,DataReaders,Recordsets ...哦,我的!從SQL Server數據庫獲取數據

假設我已經連接到打開的DB。我只是希望做這樣的事情:

Dim age As Integer = <SQL statement here> 

回答

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(); 

不是VB.Net的人,但我認爲這將是這個樣子在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() 
+0

哈哈! C#人很難使用分號! :d –

4

試着這麼做這個:

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