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

本文关键字:两个 数据 插入 初始化 属性 连接 | 更新日期: 2023-09-27 18:16:16

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是主键在表学生和外键在课程

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

你的查询应该是这样的

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期:前两个命令

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,因为一旦您完成执行,将自动关闭您的连接。