7
6

More than 5 years have passed since last update.

SQL Server Compact Editionのデータベースファイル(.sdf)を作る

Last updated at Posted at 2014-11-26

Visual Studio 2013からはSQL Server Compact Editionはサポートされなくなりました。
公式には、「SQL Server 2012/2014 ExpressのLocalDBを使え」または「SQLiteを使え」ってことのようなのですが、そうはいってもいろいろ都合があってSQLCEを使いたい場合もありますよね。
そういう時はどうすればいいかというと、System.Data.SqlServerCe.dll アセンブリに含まれる System.Data.SqlServerCe.SqlCeEngineクラスのオブジェクトを生成してCreateDatabase()メソッドを呼べば、.sdfファイルが作られます。

PowerShellで書いた例が、Jeremiah Clark's Blog にありましたのでまるっと参照します。

$binpath = "C:\Program Files\Microsoft SQL Server Compact Edition\v4.0\Desktop\";
[Reflection.Assembly]::LoadFile("$binpath\System.Data.SqlServerCe.dll")
$connectionString = "Data Source='C:\temp\testDB.sdf';"

$engine = New-Object "System.Data.SqlServerCe.SqlCeEngine" $connectionString
$engine.CreateDatabase()
$engine.Dispose()

$connection = New-Object "System.Data.SqlServerCe.SqlCeConnection" $connectionString
$command = New-Object "System.Data.SqlServerCe.SqlCeCommand"
$command.CommandType = [System.Data.CommandType]"Text"
$command.Connection = $connection

$connection.Open()

$command.CommandText = "CREATE TABLE [Files] ([Id] int NOT NULL  IDENTITY (1,1), [Name] nvarchar(450) NOT NULL);"
$command.ExecuteNonQuery()        

$command.CommandText = "ALTER TABLE [Files] ADD CONSTRAINT [PK_Files] PRIMARY KEY ([Id]);"
$command.ExecuteNonQuery()

$command.CommandText = "CREATE UNIQUE INDEX [IX_Files_Value] ON [Files] ([Name] ASC);"
$command.ExecuteNonQuery()

$command.Dispose()
$connection.Close();
$connection.Dispose;
7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6