string s= @"Data Source=.\SQLEXPRESS;Initial Catalog=学生管理系统;Integrated Security=True";
string sq = "Insert Into Student(StudentName,StudentNum,StudentSex,StudentAge,StudentSdept) Values('"; sq += textBox1.Text + "' , '"; sq += textBox2.Text + "' , '"; sq += textBox3.Text + "','"; sq += textBox4.Text + "','"; sq += textBox5.Text + "') , Insert Into Accommodation(DorID) Values('"; sq += textBox6.Text + "')"; SqlConnection conn=new SqlConnection(s); conn.Open(); SqlCommand da=new SqlCommand(sq, conn); da.ExecuteNonQuery(); //执行SQL语句 conn.Close(); //关闭数据库连接
string sq = "Insert Into Student(StudentName,StudentNum,StudentSex,StudentAge,StudentSdept) Values('"; sq += textBox1.Text + "' , '"; sq += textBox2.Text + "' , '"; sq += textBox3.Text + "','"; sq += textBox4.Text + "','"; sq += textBox5.Text + "') , Insert Into Accommodation(DorID) Values('"; sq += textBox6.Text + "')"; SqlConnection conn=new SqlConnection(s); conn.Open(); SqlCommand da=new SqlCommand(sq, conn); da.ExecuteNonQuery(); //执行SQL语句 conn.Close(); //关闭数据库连接
Insert Into Student (StudentName,StudentNum,StudentSex,StudentAge,StudentSdept)
Values('{0}','{1}','{2}','{3}','{4}');
Insert Into Accommodation (DorID)
Values('{5}')
"
,textBox1.Text
,textBox2.Text
,textBox3.Text
,textBox4.Text
,textBox5.Text
,textBox6.Text
);当然更好的方法是用参数注入的方式
string s = @"Data Source=.\SQLEXPRESS;Initial Catalog=学生管理系统;Integrated Security=True";
string sq1 = "Insert Into Student(StudentName,StudentNum,StudentSex,StudentAge,StudentSdept) Values('"; sq += textBox1.Text + "' , '"; sq += textBox2.Text + "' , '"; sq += textBox3.Text + "','"; sq += textBox4.Text + "','"; sq += textBox5.Text + "')";
string sq2 = "Insert Into Accommodation(DorID) Values('"; sq += textBox6.Text + "')";SqlConnection conn = new SqlConnection(s);
conn.Open();SqlCommand da = conn.CreateCommand();da.CommandText = sq1;
da.ExecuteNonQuery(); //执行SQL语句 da.CommandText = sq2;
da.ExecuteNonQuery(); //执行SQL语句
sq2 换成这样
string sq2 = "Insert Into Accommodation(DorID) Values('" + textBox6.Text + "')";