2012-03-29 185 views
0

我只是想要我的標題說。我已經閱讀了所有以前的類似帖子,但我找不到解決方案。請您把手錶放入我的代碼中嗎?編輯:我沒有得到任何異常。我只是沒有看到數據庫中的新數據 EDIT2:前4個答案不能解決我的問題,因爲我編輯了代碼並添加了executenonquery命令。無法將數據插入數據庫

int admin = 23; 
SqlConnection thisConnection = new SqlConnection(
    ConfigurationManager.ConnectionStrings[ 
    "Data Source=...;Persist Security Info=True;User ID=myusername;Password=mypassword"] 
    .ConnectionString); 
SqlCommand nonqueryCommand = thisConnection.CreateCommand(); 
thisConnection.Open(); 
nonqueryCommand.CommandText = "INSERT INTO Account (Username,Password,AdministratorId) VALUES (@username,@password,@admin)"; 

nonqueryCommand.Parameters.Add("@username", SqlDbType.VarChar, 20); 
nonqueryCommand.Parameters["@username"].Value = UsernameTextbox.Text.ToString(); 
nonqueryCommand.Parameters.Add("@password", SqlDbType.VarChar, 15); 
nonqueryCommand.Parameters["@password"].Value = PasswordTextbox.Text.ToString(); 
nonqueryCommand.Parameters.Add("@admin", SqlDbType.Int); 
nonqueryCommand.Parameters["@admin"].Value = admin; 

EDIT:nonquerycommand.ExecuteNonQuery(); 


thisConnection.Close(); 
+0

請不要用「c#」等來標題。這就是標籤的用途。 – 2012-03-29 19:39:14

+1

另外,您收到的確切例外是什麼? – 2012-03-29 19:39:27

+0

支持評論,請勿直接存儲您的密碼。首先應用強大的散列函數,並存儲*只是*散列。當你的數據庫被盜時,這會讓你頭痛不已。 – oleksii 2012-03-29 19:46:35

回答

6

您似乎並未實際執行您的查詢。在關閉連接之前執行它。

nonquerycommand.ExecuteNonQuery(); 
2

而不是

nonqueryCommand.Parameters.Add("@username", SqlDbType.VarChar,20); 
nonqueryCommand.Parameters["@username"].Value = UsernameTextbox.Text.ToString(); 

使用

nonqueryCommand.Parameters.AddWithValue("@username", UsernameTextbox.Text.ToString()); 

並執行查詢:

nonquerycommand.ExecuteNonQuery(); 
+0

爲什麼這樣更好? – Dchris 2012-03-29 19:55:37

+1

更容易維護。 – 2012-03-29 20:02:44

2

克里斯農民有錢。

添加...

nonqueryCommand.ExecuteNonQuery(); 
+0

這篇文章並沒有說它已被編輯,所以它看起來你看到克里斯的答案,然後複製它,並將其粘貼到另一個答案。我有點困惑,爲什麼你會這樣做,或者增加了什麼價值? – 2012-03-30 00:39:16

+0

我必須簡要閱讀他的回答。當我發佈這篇文章時,我在帖子中看到的所有內容都是「你似乎沒有真正執行你的查詢,請在關閉連接之前執行它」。我試圖通過向您展示如何執行您的查詢來提供幫助。 – ctorx 2012-03-30 04:19:54

+0

那就更有意義了。並且,爲了您的信任,您的案件正好適用於您的案件。 :) – 2012-03-30 14:05:25

3

兩件事情跳出立即在這裏。

  1. 當您檢索從ConfigurationManager.ConnectionStrings你應該通過在配置文件中的連接字符串的名稱連接字符串,而不是連接字符串它的自我。我懷疑你甚至可能沒有獲得有效的連接字符串。

  2. 您需要在nonqueryCommand實例上調用ExecuteNonQuery()

0

必須指定連接執行查詢 爲附加以下thisConnection.Open前行之前,命令();

nonqueryCommand.Connection=thisConnection; 
+0

如果您使用connection.CreateCommand作爲op已經完成,連接已被分配給該命令的實例。 – 2012-03-30 17:36:30

0

,你必須執行查詢並關閉在此之後您的連接如下圖所示

nonquerycommand.ExecuteNonQuery(); 

,或者如果你想,如果執行的查詢或檢查不這樣做

if(nonquerycommand.ExecuteNonQuery()>0){ //some message or function } 

返回的值是該語句影響的行數。