19

プログラムで 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);
    }
}

このアプリケーションを 2 回目に実行すると、例外が発生します。

「データベースには「Customer」という名前のオブジェクトが既に存在します」

しかし、データベースをチェックすると、そのようなテーブルは表示されません。
これが私の接続文字列です。

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

選択クエリを実行しているとき。既存のテーブルから結果を取得しているので、接続文字列は問題ないと思います。問題が表示されることを願っています:/

4

7 に答える 7

12

Initial catalog接続文字列で名前について言及していません。データベース名を名前としてInitial Catalog付けます。

<add name ="AutoRepairSqlProvider" connectionString=
     "Data Source=.\SQLEXPRESS; Initial Catalog=MyDatabase; AttachDbFilename=|DataDirectory|\AutoRepairDatabase.mdf;
     Integrated Security=True;User Instance=True"/>
于 2013-10-25T11:54:16.160 に答える
9

まず、テーブルが存在するかどうかを確認します。したがって、テーブルが存在しない場合は作成します。

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();
于 2013-10-25T12:00:22.750 に答える
1

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();
于 2015-12-23T14:59:09.017 に答える
0
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();
        }
    }
}
于 2015-12-21T05:59:33.777 に答える