2015-10-06 73 views
3
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单一形式两个表中插入数据插入数据表的学生和外键主键当然连接属性未初始化。我试图以两种表

+0

希望您了解SQL注入。 –

+3

你知道你正在创建的前两个SqlCommand没有被使用,对吧? –

+0

您的第一个两个命令不会执行。只有第三个命令会执行,因为您将两次替换命令cmd。 –

回答

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

感谢您的回复。 – newincsharp

+0

我已经改变了最后一个命令的工作。 – newincsharp

+0

cmd = new SqlCommand(“更新课程设置coursename = @ coursename where course.stid =(选择顶部(1)stid从课程顺序stid desc)”,con); cmd.Parameters.AddWithValue(“@ coursename”,comboBox1.Text.ToString()); – newincsharp

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因为这会为你自动关闭连接一旦你完成与你的执行。

+0

他正在使用连接属性和SQLCommand – andy

相关问题