我是asp.net的新手。我想从数据库表中选择值。
如果它是PHP,我会像下面的代码一样。
$query = mysql_query(" SELECT * FROM Table WHERE id = ".$d." ");
while($row = mysql_fetch_array($query))
{
$firstname = $row['firstname'];
$lastname = $row['lastname'];
}
如果我在asp.net中使用SqlConnection ...和SqlCommand,或者如果有一些beter Connections,我该怎么办....
提前谢谢你们... ..
答案 0 :(得分:0)
//Create a command, using a parameter
var command = new SqlCommand("select firstname, lastname from table where id=@id");
command.Parameters.AddWithValue("id", id);
DataTable dt = new DataTable();
//use a using statement to ensure the connection gets disposed properly
using(var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
//execute the command and load the results in a data table
dt.Load(command.ExecuteReader());
}
//loop through the results of the data table
foreach(var row in dt.Rows)
{
var firstname = row.Field<string>("firstname");
var lastname = row.Field<string>("lastname");
//do something with firstname and lastname
}
这不是直接翻译,因为我将值存储在DataTable
中,但这通常比打开数据连接更好。