【问题标题】:Can't Create The Same Table Twice in SQL Server无法在 SQL Server 中两次创建同一个表
【发布时间】:2011-02-23 01:29:45
【问题描述】:

我有一个 C# Windows 窗体应用程序。我按下一个按钮,它应该创建一个表并插入一个值(int)。 我将初始数据库创建为服务数据库(添加新项目 > 数据 > 服务数据库)。

按钮的代码是(输出如下):

private void button1_Click(object sender, EventArgs e)
{
    SqlConnection thisConnection = new SqlConnection(Properties.Settings.Default.Database1ConnectionString);
    SqlCommand nonqueryCommand = thisConnection.CreateCommand();

    try
    {
        thisConnection.Open();

        nonqueryCommand.CommandText = "CREATE TABLE MyTable1 (intColumn int)";
        Console.WriteLine(nonqueryCommand.CommandText);
        Console.WriteLine("Number of Rows Affected is: {0}", nonqueryCommand.ExecuteNonQuery());

        nonqueryCommand.CommandText = "INSERT INTO MyTable1 VALUES (99)";
        Console.WriteLine(nonqueryCommand.CommandText);
        Console.WriteLine("Number of Rows Affected is: {0}",
           nonqueryCommand.ExecuteNonQuery());
    }
    catch (SqlException ex)
    {
        Console.WriteLine(ex.ToString());
    }
    finally
    {
        thisConnection.Close();  // close connection
        Console.WriteLine("Connection Closed.");
    }
}

输出: 创建表 MyTable1 (intColumn int) 受影响的行数是:-1 插入 MyTable1 值 (99) 受影响的行数是:1 连接已关闭。

即使我将其关闭并重新连接,也没有其他表出现在服务器资源管理器上。

如果我按下按钮使其再次发出相同的声音,我会得到:

System.Data.SqlClient.SqlException (0x80131904): There is already an object named 'MyTable1' in the database.

但服务器资源管理器上仍然没有任何内容。

【问题讨论】:

  • 你大喊大叫有什么原因吗?

标签: c# sql-server visual-studio-2010


【解决方案1】:

异常告诉你到底发生了什么。您的表已经存在。您无法再次创建它。如果表已经存在,则需要 DROP。

【讨论】:

  • 我认为他的抱怨是该表似乎不以某种方式存在(他无法通过他的 SQL 客户端发现它)。
【解决方案2】:

即使我将其关闭并重新连接,也没有其他表出现在服务器资源管理器上。

每当您执行程序时,Visual Studio 的项目管理会自动在部署文件夹 Debug\Bin 中部署(复制该数据库).mdf 数据库文件。我认为您的代码使用了位于 Debug\Bin 文件夹中的数据库(不会在服务器资源管理器中显示),而 Server Explorer 显示了一个数据库 (.mdf)位于项目文件夹的根目录,为空。

【讨论】:

  • 那么你如何检查数据库在做什么?
  • @Richard :我从你的问题描述中猜到了。请验证您的连接字符串,我确定您的 app.config 文件中的 connectionString 使用了 |DataDirectory|替代品。
  • 数据源=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\WikiTest.mdf;Integrated Security=True;User Instance=True
  • 你有两个数据库 - 第一个放在你的项目文件夹下,它是空的。第二个数据库复制到 Debug\Bin 下并由您的代码使用。在“connectionstring”中使用项目文件夹数据库的绝对路径。例如...AttachDbFilename=c:\folder\project_folder\WikiTest.mdf;..
【解决方案3】:

尝试指定 SqlCommand 的 commandType 属性 = CommandType.Text

还要确保您连接到同一个 SQL 实例。您可以通过在打开连接后断点该行来获取您的代码(因为它是在您知道它有效的时候)并去寻找服务器名称。

请注意,您可以在一台机器上拥有多个 SQL 实例...因此您可以在正确的服务器(例如 localhost)上工作,但没有访问正确的实例(例如 SQLEXPRESS 而不是 MSSQLSERVER)。

【讨论】:

  • -1:这有什么帮助?它在他第一次点击按钮时正确执行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 2013-11-05
  • 1970-01-01
  • 2018-07-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多