我已经阅读过所有以前类似的帖子,但我找不到解决方案。你能看一下我的代码吗?我没有任何例外。我只是没有在数据库中看到新数据。
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 :(得分: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();
您需要修复连接字符串。
答案 1 :(得分:1)
我不确定这是否是错误,但ConnectionStrings
中的ConfigurationManager
索引器正在寻找连接字符串的名称:
<connectionStrings>
<add name="SomeDB" connectionString="..." />
</connectionStrings>
ConfigurationManager.ConnectionStrings["SomeDB"].ConnectionString
我认为这会导致代码出错,可能是空引用异常,但我不记得该类是如何工作的。
答案 2 :(得分:0)
我认为您错误地拉动了连接字符串。 ConfigurationManager.Connectionstrings是在app / web.config文件中的连接字符串名称上键入的。尝试使用.config文件中的名称,或者只是将连接字符串硬编码到SqlConnection对象构造函数中。
答案 3 :(得分:0)
SqlConnection thisConnection = new SqlConnection(
ConfigurationManager.ConnectionStrings["NameOfConnectionString"].ConnectionString);