连接属性未初始化。我试图在两个表中插入数据

时间:2015-10-06 07:29:15

标签: c#

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是表student和主键中的主键

2 个答案:

答案 0 :(得分:0)

您的查询应该是这样的

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();

答案 1 :(得分:0)

您的代码中存在一些问题:

问题1:前两个命令

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);

未被使用。您需要使用ExecuteNonQuery来执行它们。目前只执行第三个命令。

你得到的错误

  

连接属性未初始化

是因为您需要将连接分配给SqlCommand。

问题2:您的代码对SQL注入是开放的。您需要使用参数化查询来摆脱它。(强烈建议。

问题3 :尝试使用using语句来处理SqlConnection,因为一旦执行完毕,这会自动关闭您的连接。