2011-10-27 5 views
1

データベースから単一の値を取得する最も簡単な方法を探しています。これは.NET言語でこれを行うために存在する9,000の方法すべてを検討すると混乱します。 SqlCommands、DataReaders、Recordsets ... oh my!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 
関連する問題