【问题标题】:C# - Create SQL Server table programmaticallyC# - 以编程方式创建 SQL Server 表
【发布时间】:2013-11-04 12:33:30
【问题描述】:

我正在尝试以编程方式创建 SQL Server 表。这是代码。

using (SqlConnection con = new SqlConnection(conStr))
{

    try
    {
        //
        // Open the SqlConnection.
        //
        con.Open();
        //
        // The following code uses an SqlCommand based on the SqlConnection.
        //
        using (SqlCommand command = new SqlCommand("CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
            command.ExecuteNonQuery();

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

当我第二次运行这个应用程序时,我遇到了一个异常:

“数据库中已经有一个名为‘客户’的对象”

但是当我检查数据库时,我没有看到这样的表。
这是我的连接字符串。

<connectionStrings>
  <add name ="AutoRepairSqlProvider" connectionString=
     "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
     Integrated Security=True;User Instance=True"/>
</connectionStrings>

当我运行选择查询时;我从现有表中得到结果,所以我认为连接字符串应该没问题。希望你能看到问题:/

【问题讨论】:

  • 尝试刷新您的 SQL 资源管理器窗口 :)
  • 这是不可能的 ;) 您正在检查不正确的数据库或表存在,但由于某种原因您看不到。
  • 我正在检查正确的数据库,因为我可以从中读取数据

标签: c# .net sql-server create-table


【解决方案1】:

您没有在连接字符串中提及Initial catalog 名称。将您的数据库名称命名为 Initial Catalog 名称。

<add name ="AutoRepairSqlProvider" connectionString=
     "Data Source=.\SQLEXPRESS; Initial Catalog=MyDatabase; AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
     Integrated Security=True;User Instance=True"/>

【讨论】:

  • 哦!数据库名称不是他们在他的连接字符串。但是如何显示这个错误信息There is already an object named 'Customer' in the database ??
  • @Ramesh - 您可能已经在“主”数据库中创建了“客户”。
【解决方案2】:

首先,检查表是否存在。因此,如果不存在则创建表。

var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";

using (SqlCommand command = new SqlCommand(commandStr, con))
command.ExecuteNonQuery();

【讨论】:

    【解决方案3】:

    为了在 SQL Server 中管理数据库对象,我建议使用Server Management Objects

    【讨论】:

    • 这应该是正确且被接受的答案。上面的一切都是古老的技术
    【解决方案4】:

    试试这个

    检查表是否存在,然后删除表,然后创建

    using (SqlCommand command = new SqlCommand("IF EXISTS (
    SELECT *
    FROM sys.tables
    WHERE name LIKE '#Customer%')
    DROP TABLE #Customer CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime);", con))
    

    【讨论】:

      【解决方案5】:

      如果你不喜欢记住 SQL 语法,使用 Mig# 你可以简单地:

      var schema = new DbSchema(ConnectionString, DbPlatform.SqlServer2014);
      schema.Alter(db => db.CreateTable("Customer")
           .WithPrimaryKeyColumn("Id", DbType.Int32).AsIdentity()
           .WithNotNullableColumn("First_Name", DbType.String).OfSize(50)
           .WithNotNullableColumn("Last_Name", DbType.String).OfSize(50)
           ...);
      

      如果您不确定它是否已经存在,请致电DropIfExists

      db.Tables["Customers"].DropIfExists();
      

      【讨论】:

        【解决方案6】:
        using System;
        using System.Data;
        using System.Data.SqlClient;
        
        namespace SqlCommend
        {
            class sqlcreateapp
            {
                static void Main(string[] args)
                {
                    try
                    {
                        SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
                        SqlCommand cmd = new SqlCommand("create table <Table Name>(empno int,empname varchar(50),salary money);", conn);
                        conn.Open();
                        cmd.ExecuteNonQuery();
                        Console.WriteLine("Table Created Successfully...");
                        conn.Close();
                    }
                    catch(Exception e)
                    {
                        Console.WriteLine("exception occured while creating table:" + e.Message + "\t" + e.GetType());
                    }
                    Console.ReadKey();
                }
            }
        }
        

        【讨论】:

        • 请添加更多细节
        【解决方案7】:

        试试这个:

        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
            try
            {
                cn.Open();
                SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
                cmd.ExecuteNonQuery();
                lblAlert.Text = "SucessFully Connected";
                cn.Close();
            }
            catch (Exception eq)
            {
                lblAlert.Text = eq.ToString();
            }
        }
        

        【讨论】: