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

标签 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 是表学生中的主键和类(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/

相关文章:

未输入任何值时,C# TextBox to int() 不工作

c# - 防止用户两次提交表单的好方法是什么?

c# - 确定文本文件中使用的行结尾

C# Nhibernate 保存列表

c# - 如何在 C# 中通过 POST HttpWebRequest 发送 PDF

c# - 找不到段 'Property' 的资源

c# - MySQL(或 C#)不匹配 double 或小数

c# - 如何传递空值颜色

c# - XmlWriter.WriteRaw 在通过 XElement.CreateWriter 创建编写器时转义 xml

c# - 如何使用 Word Automation 在段落中添加下标字符?