asp.net print the results of a sql command
I have the following sql command:
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con);
How can i output the results开发者_如何学C of the following command in C# to my webpage?
If you are looking for the introductory: "How to get data on a web page?" answer, then maybe this is a little more helpful:
- Add a new page MyPage.aspx to your web application
- Add a GridView to that page
- On Page_Load do the code below
{
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();
}
You will need to execute the SQL command, then iterate through the data. Assuming this query returns one row, your code might look like:
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"];
}
}
精彩评论