无法将数据插入SQL Server数据库

本文关键字:SQL Server 数据库 插入 数据 | 更新日期: 2023-09-27 18:29:38

我已经阅读了以前所有类似的帖子,但我找不到解决方案。你能看看我的代码吗?我没有任何例外。我只是在数据库中看不到新数据。

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();

无法将数据插入SQL Server数据库

您正在使用连接字符串对连接字符串集合进行索引?

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();

你需要修复连接字符串。

我不确定这是否是一个错误,但ConfigurationManager中的ConnectionStrings索引器正在查找连接字符串的名称

<connectionStrings>
    <add name="SomeDB" connectionString="..." />
</connectionStrings>
ConfigurationManager.ConnectionStrings["SomeDB"].ConnectionString

不过,我认为这会导致代码中出现错误,可能是null引用异常,但我不记得那个类是如何工作的。

我认为您拉错了连接字符串。ConfigurationManager.Connectionstring基于app/web.config文件中连接字符串的名称。请尝试使用.config文件中的名称,或者将连接字符串硬编码到SqlConnection对象构造函数中。

SqlConnection thisConnection = new SqlConnection(
    ConfigurationManager.ConnectionStrings["NameOfConnectionString"].ConnectionString);