您好,我製作了manullay創建的文本框,然後將其用於創建新用戶。我使用SQL SERVER 2005作爲後端和Visual Server 2008作爲前端。我有這個LoginAccount表,它存儲了創建的新用戶的詳細信息。當我點擊該按鈕(在我所編寫的代碼創建通過SQL插入一個新的用戶),通過C#將值插入到SQL表中時出現異常
string strConnection = ConfigurationManager.ConnectionStrings"FHDLConnectionString"].ToString();
SqlConnection sqlConnection = new SqlConnection(strConnection);
string username = TextBox1.Text;
string password = TextBox2.Text;
string confirmpass = TextBox3.Text;
string SQLQuery = "Select username From LoginAccount where '" + username + "'";
string SQLQuery1 = "Insert into LoginAccount values ('" + username + "','" + password + "')";
SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
SqlCommand command1 = new SqlCommand(SQLQuery1, sqlConnection);
sqlConnection.Open();
string CheckUsername = "";
if (password.ToString() != confirmpass.ToString())
{
Literal1.Text = " Password's does not match ";
}
else
{
try
{
CheckUsername = command.ExecuteScalar().ToString();
}
catch (Exception er)
{
Literal1.Text = " Username already exists ";
}
string insertQuery = "";
try
{
insertQuery = command1.ExecuteScalar().ToString();
Server.Transfer("Login_Created.aspx");
}
catch (Exception er)
{
Literal1.Text = " Could not create the user, Please retry with some other option ";
}
}
sqlConnection.Close();
我得到這些異常的
在指定的非布爾類型的表達式情境了條件,預計,不久的「fhdl」 這個錯誤我得到的第一個catch
和
未將對象引用設置爲對象的實例。 這是最後一次。
但更主要的是,我能夠插入用戶名和密碼進入登錄賬號表!!!!!!!即當我看到表格內容時,我可以看到在該表格中創建的新用戶。 另一件事是完美前一次,但不執行該代碼現在:( 請任何人都可以告訴我,我要去哪裏錯了 我是新來的C#與SQL ...
謝謝..該死的我一遍又一遍地查看了整個代碼,但沒有發現這樣愚蠢的錯誤...... – 2010-07-23 09:36:13
沒問題......正如cryss說的,雖然這個代碼還有其他問題。使用sql參數而不是構建sql字符串。在你需要它們之前不要創建命令對象。使用子句包裝連接和命令對象。我不確定Server.Transfer是否會殺死當前線程,但如果它確實存在,那麼sql連接永遠不會關閉。 (使用會解決這個問題)。 享受 – 2010-07-23 12:53:27