SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["abc"].ConnectionString);
SqlCommand cmd;
cmd = new SqlCommand("insert into student (name,email,mobile,userid,pass) values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"')", con);
cmd = new SqlCommand("insert into course (stid) select top (1) stid from student order by stid desc", con);
cmd = new SqlCommand("update course set coursename ='"+comboBox1.Text+"'where stid = top (1) stid from course order by stid desc",con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
我正在尝试使用具有主键和外键关系的单一表单在两个表中插入数据 stid 是表学生中的主键和类(class)中的外键
最佳答案
你的查询应该是这样的
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["abc"].ConnectionString);
SqlCommand cmd;
con.Open();
cmd = new SqlCommand("insert into student (name,email,mobile,userid,pass) values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"')", con);
cmd.ExecuteNonQuery();//Foreach query you need to execute this line
cmd = new SqlCommand("insert into course (stid) select top (1) stid from student order by stid desc", con);
cmd.ExecuteNonQuery();//Foreach query you need to execute this line
cmd = new SqlCommand("update course set coursename ='"+comboBox1.Text+"'where stid = top (1) stid from course order by stid desc",con);
cmd.ExecuteNonQuery();//Foreach query you need to execute this line
con.Close();
关于c# - 连接属性未初始化。我试图在两个表中插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32964148/