namespace WpfApplication2 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } //连接字符串 string constr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString; private void button1_Click(object sender, RoutedEventArgs e) { using (SqlConnection conn = new SqlConnection(constr)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select waterwork from Table_1 where othersnum=@num"; cmd.Parameters.Add(new SqlParameter("@num", textBox1.Text)); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { string work = reader.GetString(0); MessageBox.Show(work); } } } } } private void btnDataSet1_Click(object sender, RoutedEventArgs e) { using(SqlConnection conn=new SqlConnection (constr)) { using(SqlCommand cmd=conn.CreateCommand()) { cmd.CommandText = "select * from Table_1"; SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet dataset = new DataSet(); adapter.Fill(dataset); //foreach(DataRow row in dataset.Tables[0].Rows) //{ // int waternum = (int)row["waterwork"]; // MessageBox.Show(waternum.ToString()); //} DataTable table = dataset.Tables[0]; DataRowCollection rows = table.Rows; for (int i = 0; i < rows.Count;i++ ) { DataRow r = rows[i]; string waternum = (string)r["waterwork"]; MessageBox.Show(waternum); } } } } } }
App.config配置文件
1 <?xml version="1.0" encoding="utf-8" ?> 2 <configuration> 3 <connectionStrings> 4 <add name="ConnStr" connectionString="Data Source=.;Initial Catalog=master;User ID=sa;Password=123456;"/> 5 </connectionStrings> 6 </configuration>