使用DataAdapter和DataSet來讀取數據表JBQK中的數據
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace shiyan11 { class Program { static void Main(string[] args) { string strCon = @"Data Source = .\SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True;"; SqlConnection sqlCon = new SqlConnection(strCon); try { sqlCon.Open(); string sqlStr = @"select No,Name,Grade from JBQK"; SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlCon); SqlDataAdapter sda = new SqlDataAdapter(sqlCmd); DataSet ds = new DataSet(); sda.Fill(ds); //填充數據集,實質是填充ds中的第0個表 string sltResult = ""; DataTable dt = ds.Tables[0]; Console.WriteLine("基本情況數據表查詢結果如下:"); for (int i = 0; i < dt.Rows.Count;i++ ) { //逐行讀取,每行通過字段名或者索引來訪問 sltResult += "第" + (i + 1) + "記錄:" + dt.Rows[i][0].ToString() + "\t" + dt.Rows[i]["Name"].ToString() + dt.Rows[i][2].ToString() + "\n"; } Console.WriteLine(sltResult); } catch (Exception e) { Console.WriteLine("失敗!!"); } sqlCon.Close(); Console.Read(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace shiyan11 { class Program { static void Main(string[] args) { string strCon = @"Data Source = .\SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=True;"; SqlConnection sqlCon = new SqlConnection(strCon); try { sqlCon.Open(); string sqlStr = @"select No,Name,Grade from JBQK"; SqlCommand sqlCmd = new SqlCommand(sqlStr, sqlCon); SqlDataAdapter sda = new SqlDataAdapter(sqlCmd); DataSet ds = new DataSet(); sda.Fill(ds); //填充數據集,實質是填充ds中的第0個表 string sltResult = ""; //---------------------------------------------- //以sda為參數來初始化SqlCommandBuilder實力 SqlCommandBuilder scb = new SqlCommandBuilder(sda); //刪除DataSet中數據表JBQK中的第一行數據 ds.Tables[0].Rows[0].Delete(); //調用Update方法,以DataSet中的數據更新數據庫 sda.Update(ds, ds.Tables[0].ToString()); ds.Tables[0].AcceptChanges(); //---------------------------------------------- DataTable dt = ds.Tables[0]; Console.WriteLine("基本情況數據表查詢結果如下:"); for (int i = 0; i < dt.Rows.Count;i++ ) { //逐行讀取,每行通過字段名或者索引來訪問 sltResult += "第" + (i + 1) + "記錄:" + dt.Rows[i][0].ToString() + "\t" + dt.Rows[i]["Name"].ToString() + dt.Rows[i][2].ToString() + "\n"; } Console.WriteLine(sltResult); } catch (Exception e) { Console.WriteLine(e.ToString()); } sqlCon.Close(); Console.Read(); } } }