使用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(); } } }
蜗牛—C#程设之DataAdapter对象,布布扣,bubuko.com
原文:http://blog.csdn.net/qq1791422018/article/details/27359629