using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Data.SqlClient; using System.Data; using System.Configuration;
namespace _03.DataSet离线数据集 { /// <summary> /// Window1.xaml 的交互逻辑 /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); }
private void btnDS_Click(object sender, RoutedEventArgs e) { using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=MyTest;User Id=sa;Password=123;")) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select * from T_Student where age<@age"; cmd.Parameters.Add(new SqlParameter("@age", 60)); //cmd.ExecuteReader();并没有执行,而是new了一个adapter来接受cmd。
//SqlDataAdapter是一个帮我们把SqlCommand的查询结果填充到DataSet中的类 SqlDataAdapter adapter = new SqlDataAdapter(cmd);//SqlDataAdapter需要一个参数
//DataSet相当于本地的一个复杂集合(List<int>) DataSet dataset = new DataSet();//DataSet是数据集 adapter.Fill(dataset);//执行cmd并且把SqlCommand查询结果填充到DataSet
//DataTable是内存中的数据表 DataTable table = dataset.Tables[0];//因为数据库中就一个表T_Student,所以就是[0]. DataRowCollection rows = table.Rows;//DataRowCollection是DataTable行的集合,这里的rows指查询结果的行 for (int i = 0; i < rows.Count; i++) { DataRow row = rows[i]; int age = (int)row["Age"]; string name=(string)row["Name"]; MessageBox.Show(name+","+age); } } } }
MessageBox.Show(connStr); using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select * from T_Student where age<@age"; cmd.Parameters.Add(new SqlParameter("@age",21));
SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet dataset = new DataSet(); adapter.Fill(dataset);