2015-10-06 35 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

相關問題