2012-03-29 153 views
0

我已閱讀所有以前的類似帖子,但找不到解決方案。你能看看我的代碼嗎?我沒有任何例外。我只是看不到數據庫中的新數據。無法將數據插入到SQL Server數據庫中

int admin = 23; 

SqlConnection thisConnection = new SqlConnection(
    ConfigurationManager.ConnectionStrings["myconnectionstring"].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; 

nonquerycommand.ExecuteNonQuery(); 

thisConnection.Close(); 
+0

您是否收到錯誤信息?或者什麼都沒有發生? – 2012-03-29 20:06:01

+0

乍一看對我來說很好。你確定你沒有(無意中)使用一個正在被自動回滾的交易嗎? – 2012-03-29 20:06:39

+1

不要複製你的問題。 (http://stackoverflow.com/questions/9932254/cannot-insert-data-into-database) – 2012-03-29 20:07:02

回答

1

我不知道這是否是一個錯誤或沒有,但ConnectionStrings索引在ConfigurationManager正在尋找名稱的連接字符串的

<connectionStrings> 
    <add name="SomeDB" connectionString="..." /> 
</connectionStrings> 

ConfigurationManager.ConnectionStrings["SomeDB"].ConnectionString 

我認爲這會造成過你的代碼中有一個錯誤,也許是一個空引用異常,但我不記得那個類是如何工作的。

2

您正在使用連接字符串爲連接字符串集合編制索引嗎?

int admin = 23; 

    SqlConnection thisConnection = new SqlConnection(
"Data Source=...;Persist Security Info=True;User ID=myusername;Password=mypassword"); 
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; 

nonquerycommand.ExecuteNonQuery(); 


thisConnection.Close(); 

您需要修復連接字符串。

0

我認爲你正在拉錯連接字符串。 ConfigurationManager.Connectionstrings鍵入app/web.config文件中的連接字符串的名稱。嘗試在.config文件中使用該名稱,或者僅將連接字符串硬編碼到SqlConnection對象構造函數中。

0
SqlConnection thisConnection = new SqlConnection(
    ConfigurationManager.ConnectionStrings["NameOfConnectionString"].ConnectionString); 
相關問題