在SQL Server中无法创建相同的表两次

时间:2011-02-23 01:29:46

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

我有一个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.");
    }
}
  

输出:   CREATE TABLE MyTable1(intColumn int)   受影响的行数为:-1   插入MyTable1值(99)   受影响的行数为:1   连接已关闭。

服务器资源管理器上没有显示任何内容即使我关闭它并重新连接也没有其他表。

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

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

但在服务器资源管理器上仍然没有。

3 个答案:

答案 0 :(得分:5)

异常告诉你到底发生了什么。你的桌子已经存在。你不能再创建它。如果表已经存在,则需要删除表。

答案 1 :(得分:0)

  

服务器资源管理器上没有显示任何内容即使我关闭它并重新连接也没有其他表。

无论何时执行程序,Visual Studio的项目管理都会在部署文件夹 Debug \ Bin 中自动部署(复制该数据库).mdf数据库文件。我认为您的代码使用的数据库位于 Debug \ Bin 文件夹(将不会显示在服务器资源管理器中),服务器资源管理器显示数据库(.mdf)位于项目文件夹的根目录,它是空的。

答案 2 :(得分:-2)

尝试spceifying SqlCommand = CommandType.Text

的commandType属性

还要确保连接到同一个SQL实例。您可以在打开连接之后通过断开线来获取代码(当您知道它有效时),并寻找服务器名称。

请注意,您可以在一台计算机上安装多个SQL实例...这样您就可以使用正确的服务器(例如localhost),但却无法访问正确的实例(例如SQLEXPRESS而不是MSSQLSERVER)。