我有以下sql命令:
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con);
如何将C#中以下命令的结果输出到我的网页?
答案 0 :(得分:2)
如果您正在寻找介绍:“如何在网页上获取数据?”回答,那么也许这会更有帮助:
{
string strSQLconnection =
"Data Source=dbServer;Initial Catalog=yourDatabase;Integrated Security=True";
SqlConnection con = new SqlConnection(strSQLconnection);
SqlCommand sqlCommand =
new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con);
con.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
答案 1 :(得分:0)
您需要执行SQL命令,然后遍历数据。假设此查询返回一行,您的代码可能如下所示:
using (var reader = cmd.ExecuteReader()) {
if (!reader.HasRows) {
// User not found
}
else {
reader.Read(); // Advance to first row
// Sample data access
var name = reader["name"];
var otherColumnValue = reader["otherColumnName"];
}
}