寻找从数据库中获取单个值的最简单方法。当你考虑在.NET语言中存在的所有9,000种方法时,这会让人感到困惑。 SqlCommands,DataReaders,Recordsets ......哦,我的!
假设我已经打开了与数据库的连接。我只是想做这样的事情:
Dim age As Integer = <SQL statement here>
答案 0 :(得分: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()
答案 1 :(得分: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