ASP.NET中 C#訪問資料庫用三種方式顯示資料表
第一種方式:使用DataReader從資料庫中每次提取一條資料,用迴圈遍歷表
下面是我寫的一個例子:
string linkstr=
@"DataSource=.\SQLEXPRESS;AttachDbFilename=C:\Users\Administrator\Desktop\netSQL\Book Sample.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; //連線字串
string sql = "select * from students"; //定義sql語句
SqlCommand comm = new SqlCommand(sql, conn);//定義並例項化命令
SqlDataReader reader = comm.ExecuteReader(); //定義DataReader
Response.Write("<table cellspacing='0'>");
while (reader.Read())
{
Response.Write("<tr>");
for (int i = 0; i < reader.FieldCount; i++)
Response.Write("<td style='border:solid 1px Gray;'>" +
reader[i].ToString() + "</td>");
Response.Write("</tr>");
}
Response.Write("</table >");//將DataRead讀取的內容用迴圈一條條寫入網頁,形成一個數據表
reader.Close(); conn.Close();//關閉連線,釋放資源
第二種方式:使用DataTable從資料庫中讀取一個數據表,用迴圈輸出這個表
(程式碼中的資料介面卡DataAdapter經常和DataSet配合使用,作為DataSet 和資料來源之間的橋接器以便檢索和儲存資料。而DataSet由一組DataTable物件組成,它具備儲存多個數據表以及表間關係的能力。資料表儲存在DataTable物件中,表間的關係用DataRelation物件表示。)
string linkstr =
@"DataSource=.\SQLEXPRESS;AttachDbFilename=C:\Users\Administrator\Desktop\netSQL\BookSample.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; //連線字串
string sql = "select * from students"; //定義sql語句SqlConnection conn = new SqlConnection(linkstr); //定義並例項化連線
SqlCommand comm = new SqlCommand(sql, conn); //定義並例項化命令
SqlDataAdapter ada = new SqlDataAdapter(comm); //定義資料介面卡
DataTable dt = new DataTable();
ada.Fill(dt);
Response.Write("<table cellspacing='0'>");
for (int i = 0; i < dt.Rows.Count; i++)
{
Response.Write("<tr>");
for (int j = 0; j < dt.Columns.Count; j++)
Response.Write("<td style='border:solid 1px Gray;'>" +
dt.Rows[i][j].ToString() + "</td>");
Response.Write("</tr>");
}
Response.Write("</table >");//迴圈輸出DataTable中每一行每一列的內容
conn.Close();
第三種方式:使用程式碼連線資料庫,填充資料表DataTable,再為GridView控制元件繫結資料來源
string linkstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Administrator\Desktop\netSQL\BookSample.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; //連線字串
string sql = "select * from students";
SqlConnection conn = new SqlConnection(linkstr);
SqlCommand comm = new SqlCommand(sql, conn);
SqlDataAdapter ada = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
ada.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();//為GridView繫結資料來源(首先得在網頁新增一個GridView控制元件)