实验目的:
学习增、删、改、查操作。
实验内容:
学习增删改查操作
目标效果:
实验步骤:
1、数据库数据准备:
需要在数据库里准备一张表,以便下面可以进行使用
2、创建新项目:
3、根据目标效果从工具箱添加控件:
(1)添加”DataGridView“,并且连接数据(具体步骤参考:数据库实验2)
(2)添加控件:
4、设置“增”按钮的点击事件:
private void Insert_Click(object sender, EventArgs e)
{
String StuID = textBox1.Text.Trim();
String StuName = textBox2.Text.Trim();
String StuSex = textBox3.Text.Trim();
String StuAge = textBox4.Text.Trim();
String StuSdept = textBox5.Text.Trim();
try
{
con.Open();
string insertStr = "INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept) " +
"VALUES('" + StuID + "','" + StuName + "','" + StuSex + "'," + StuAge + ",'" + StuSdept + "')";
SqlCommand cmd = new SqlCommand(insertStr, con);
cmd.ExecuteNonQuery();
}
catch
{
MessageBox.Show("输入数据违反要求");
}
finally
{
con.Dispose();
}
this.studentTableAdapter.Fill(this.sCHOOLDataSet.Student);
}
注意事项:
string insertStr = "INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept) " +
"VALUES(" + StuID + "," + StuName + "," + StuSex + "," + StuAge + "," + StuSdept + ")";
这么写是错误的,等价的SQL语句为:
INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept) VALUES(201215134,秦修,男,23,FM)
和数据库里定义的属性是不相符合的,要根据属性的要求添加单引号。
5、设置“删”的点击事件:
private void Delete_Click(object sender, EventArgs e)
{
try
{
con.Open();
string select_id = dataGridView1.SelectedRows[0].Cells[0].Val