1 private void button2_Click(object sender, RoutedEventArgs e) 2 { 3 using (SqlConnection conn = new SqlConnection("Data Source=XX;Initial Catalog=DBData;User ID=sa;Password=111111")) 4 { 5 conn.Open(); 6 7 using (SqlCommand cmd = conn.CreateCommand()) 8 { 9 cmd.CommandText = "insert [DBData].[dbo].[T_Student] (Number,Name,Score) output inserted.ID values('012345','LiLei','89')"; 10 long id = (long)cmd.ExecuteScalar(); //ExecuteScalar():执行查询,返回结果集中的第一行的第 一列 11 MessageBox.Show("操作成功: i=" + id.ToString()); 12 } 13 } 14 15 } 16 17 18 19 private void button2_Click(object sender, RoutedEventArgs e) 20 { 21 using (SqlConnection conn = new SqlConnection("Data Source=XX;Initial Catalog=DBData;User ID=sa;Password=111111")) 22 { 23 conn.Open(); 24 25 using (SqlCommand cmd = conn.CreateCommand()) 26 { 27 cmd.CommandText = "Select * from [DBData].[dbo].[T_Student] where score<160"; 28 using (SqlDataReader reader = cmd.ExecuteReader()) 29 { 30 while (reader.Read()) 31 { 32 MessageBox.Show(reader.GetString(2)); //获取指定列的字符串的值 33 } 34 } 35 } 36 } 37 38 } 39 40 41 private void button2_Click(object sender, RoutedEventArgs e) 42 { 43 using (SqlConnection conn = new SqlConnection("Data Source=XX;Initial Catalog=DBData;User ID=sa;Password=111111")) 44 { 45 conn.Open(); 46 using (SqlCommand cmd = conn.CreateCommand()) 47 { 48 cmd.CommandText = "select * from [DBData].[dbo].[T_Student] where Score<@Score"; 49 cmd.Parameters.Add(new SqlParameter("@Score", 80)); 50 51 DataSet dataset = new DataSet(); 52 53 //SqlDataAdapter是一个帮我们把SqlCommand查询结果填充到DataSet中的类 54 SqlDataAdapter adapter = new SqlDataAdapter(cmd); 55 adapter.Fill(dataset); 56 57 DataTable dt = dataset.Tables[0]; 58 } 59 } 60 61 MessageBox.Show("操作成功"); 62 63 }