C# - 以编程方式创建 SQL Server 表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19589020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:22:47  来源:igfitidea点击:

C# - Create SQL Server table programmatically

c#.netsql-servercreate-table

提问by user2412672

I am trying to create a SQL Server table programmatically. Here is the code.

我正在尝试以编程方式创建 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);
    }
}

When I'm running this application second time I'm getting an exception:

当我第二次运行此应用程序时,出现异常:

"There is already an object named 'Customer' in the database"

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

but when I check database I don't see such a table.
Here is my connection string.

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

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

When I am running select query; I am getting results from existing tables so I think connection string should be OK. Hope you'll see the problem :/

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

采纳答案by Kurubaran

You haven't mentioned the Initial catalogname in the connection string. Give your database name as Initial Catalogname.

您尚未Initial catalog在连接字符串中提及名称。将您的数据库名称作为Initial Catalog名称。

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

回答by Ramesh Rajendran

Try this

尝试这个

Check if table have there , and drop the table , then create

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

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

回答by Giannis Paraskevopoulos

For managing DataBase Objects in SQL Server i would suggest using Server Management Objects

为了在 SQL Server 中管理数据库对象,我建议使用服务器管理对象

回答by Nair

First, check whether the table exists or not. Accordingly, create table if doesn't exist.

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

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

回答by Nagendra Kumar Elli

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

回答by Dejan

If you don't like remembering SQL syntax, using Mig#you can simply:

如果您不喜欢记住 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)
     ...);

If you are not sure if it already exists, call DropIfExistsbefore:

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

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

回答by Parmar Jigar

Try this:

尝试这个:

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