【问题标题】:SQL Server : not able to insert into table?SQL Server:无法插入表?
【发布时间】:2018-06-20 18:32:28
【问题描述】:

我不确定这是语法错误还是我的 IDE (Visual Studio) 有问题,但我似乎无法 insert into 我添加到项目中的表。

private void create_user_username_box_Leave(object sender, EventArgs e)
{
    // Add user/password to database when when someone leaves the area. 
    using (DbConnection connection = new SqlConnection(@"Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;"))
    {
        connection.Open();

        using (DbCommand command = new SqlCommand("INSERT INTO [dbo].[information] (id, password) VALUES (@id, @pw);"))
        {
            command.Parameters.Add(new SqlParameter("@id", create_user_username_textbox.Text));
            command.Parameters.Add(new SqlParameter("@pw", create_user_password_textbox.Text));

            command.Connection = connection;
            command.ExecuteNonQuery();
        }                
    }                
}

当我离开文本框时,我似乎收到一条错误消息,说明

无效的对象名称“dbo.information”

事实上,表是在 SQL Server 中创建的:

CREATE TABLE [dbo].[information]
(
    [Id] NVARCHAR(50) NOT NULL PRIMARY KEY, 
    [password] NVARCHAR(50) NULL
)

那为什么叫错名字呢?

【问题讨论】:

  • 您在master中创建了一个用户表!?
  • 表真的是在master 数据库中创建的吗?
  • 从不存储纯文本密码
  • 你应该为你的应用创建一个新的数据库,并在其中放置任何表格等
  • 在 VS 中再看看这张桌子在哪里。我赌错了 sql server INSTANCE 名称或 DATABASE 名称。您的桌子可能在 Northwind 或其他任何数据库中。不在master。因此,在发现正确的数据库名称后,在您的连接字符串中更改它。

标签: c# sql sql-server


【解决方案1】:

我认为这里的问题可能是连接字符串问题。

从这个示例开始,您使用的是本地数据库,这是我过去使用的示例连接字符串。

connectionString ="Data Source=.\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True"

初始目录为数据库名,integrated security = true表示对数据库使用windows认证。

所以在你的例子中它看起来像这样:

connectionString ="Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"/>

像 cmets 中提到的其他人一样,不要在 master 数据库中再次创建表,始终创建一个新表。

另外一点,个人风格是查看configuration manager 以便您在其中存储连接字符串,然后您可以轻松地从那里调用连接字符串。

【讨论】:

    【解决方案2】:

    您在连接字符串上使用master 数据库。

    您可以为自己的数据库更改master

    Server=localhost\SQLEXPRESS01;Database=master;Trusted_Connection=True;

    Server=localhost\SQLEXPRESS01;Database=MyDataBase;Trusted_Connection=True;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-22
      • 1970-01-01
      • 2018-01-15
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      相关资源
      最近更新 更多