2011-03-11 114 views
1

的結果,我有以下SQL命令:asp.net打印SQL命令

SqlCommand cmd = new SqlCommand("SELECT * FROM tbl WHERE ID = 'john' ", con); 

我怎麼能輸出以下命令在C#中的結果,我的網頁?

回答

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"]; 
    } 
} 
2

如果您正在查找介紹性內容:「如何獲取網頁上的數據?答案,那麼也許這是一個小更有益:

  1. 添加了新的一頁MyPage.aspx您 Web應用程序
  2. 一個GridView控件添加到該網頁
  3. 在Page_Load中做 下面
  4. 代碼

{

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(); 

}