开发者

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:

  1. Add a new page MyPage.aspx to your web application
  2. Add a GridView to that page
  3. 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"];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜