//向数据库中新增数据
private void button1_Click_1(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("server=.;database=作业;user=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "insert into student values(@sno,@sname,@ssex,@sbirthday,@class)"; cmd.Parameters.Clear(); cmd.Parameters.Add("@sno",textbox1.Text.Trim()); cmd.Parameters.Add("@sname", textbox2.Text.Trim()); if (rbtnan.Checked) { cmd.Parameters.Add("@ssex", "男"); } else { cmd.Parameters.Add("@ssex", "女"); } cmd.Parameters.Add("@sbirthday", dateTimePicker1.Value); cmd.Parameters.Add("@class", comboBox1.Text.Trim()); conn.Open(); int count = cmd.ExecuteNonQuery(); if (count > 0) { MessageBox.Show("执行成功,受影响行数为:" + count.ToString()); } else { MessageBox.Show("执行失败!"); } conn.Close(); }
//修改数据库中的数据
private void button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("server=.;database=作业;user=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "update student set sname=@sname,ssex=@ssex,sbirthday=@sbirthday,class=@class where sno=@sno"; cmd.Parameters.Clear(); cmd.Parameters.Add("@sno", textbox1.Text.Trim()); cmd.Parameters.Add("@sname", textbox2.Text.Trim()); if (rbtnan.Checked) { cmd.Parameters.Add("@ssex", "男"); } else { cmd.Parameters.Add("@ssex", "女"); } cmd.Parameters.Add("@sbirthday", dateTimePicker1.Value); cmd.Parameters.Add("@class", comboBox1.Text.Trim()); conn.Open(); int count = cmd.ExecuteNonQuery(); if (count > 0) { MessageBox.Show("执行成功,受影响行数为:" + count.ToString()); } else { MessageBox.Show("执行失败!"); } conn.Close(); }
//删除数据库中的数据
private void button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("server=.;database=作业;user=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "Delete from student where sno=@sno"; cmd.Parameters.Clear(); cmd.Parameters.Add("@sno", textbox1.Text.Trim()); conn.Open(); int count = cmd.ExecuteNonQuery(); if (count > 0) { MessageBox.Show("执行成功,受影响行数为:" + count.ToString()); } else { MessageBox.Show("执行失败!"); } conn.Close(); }
//查询数据库中的数据
private void button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("server=.;database=作业;user=sa;pwd=123"); SqlCommand cmd = conn.CreateCommand(); DataTable dt = new DataTable(); cmd = conn.CreateCommand(); cmd.CommandText = "select * from student"; conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); for (int i = 0; i < dr.FieldCount; i++) { dt.Columns.Add(dr.GetName(i)); } while (dr.Read()) { DataRow row = dt.NewRow(); row["sno"] = dr["sno"]; row["sname"] = dr["sname"]; row["ssex"] = dr["ssex"]; row["sbirthday"] = dr["sbirthday"]; dt.Rows.Add(row); } conn.Close(); }