Visual Studio を使用して SQL Server CE データベースで外部キー関係を作成する

2024-04-06

SQL Server CE で外部キー関係を作成する方法

SQL Server CE (Compact Edition) は、軽量なデータベースエンジンであり、デスクトップアプリケーションやモバイルアプリケーションで使用するために設計されています。

このチュートリアルでは、Visual Studio を使用して SQL Server CE データベースで外部キー関係を作成する方法を説明します。

手順

using System;
using System.Data.SQLite;

namespace CreateForeignKeyRelationship
{
    class Program
    {
        static void Main(string[] args)
        {
            // データベース接続文字列
            string connectionString = @"Data Source=MyDatabase.sdf";

            // テーブル作成
            CreateTable(connectionString);

            // 外部キー関係作成
            CreateForeignKeyRelationship(connectionString);

            // データ挿入
            InsertData(connectionString);

            // データ読み取り
            ReadData(connectionString);
        }

        static void CreateTable(string connectionString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                string sql = @"
                    CREATE TABLE Customers (
                        CustomerId INTEGER PRIMARY KEY AUTOINCREMENT,
                        FirstName TEXT,
                        LastName TEXT
                    );

                    CREATE TABLE Orders (
                        OrderId INTEGER PRIMARY KEY AUTOINCREMENT,
                        CustomerId INTEGER,
                        OrderDate DATETIME,
                        FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
                    );
                ";

                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }

        static void CreateForeignKeyRelationship(string connectionString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                string sql = @"
                    ALTER TABLE Orders
                    ADD FOREIGN KEY (CustomerId)
                    REFERENCES Customers(CustomerId)
                ";

                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }

        static void InsertData(string connectionString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                string sql = @"
                    INSERT INTO Customers (FirstName, LastName)
                    VALUES ('John', 'Doe'), ('Jane', 'Doe');

                    INSERT INTO Orders (CustomerId, OrderDate)
                    VALUES (1, '2023-01-01'), (2, '2023-02-01');
                ";

                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }

        static void ReadData(string connectionString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                string sql = @"
                    SELECT 
                        c.FirstName, 
                        c.LastName, 
                        o.OrderDate
                    FROM Customers c
                    INNER JOIN Orders o ON c.CustomerId = o.CustomerId;
                ";

                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine("{0} {1} - {2}", reader["FirstName"], reader["LastName"], reader["OrderDate"]);
                        }
                    }
                }
            }
        }
    }
}

このコードは、次のことを行います。

  • CustomersOrders という名前の 2 つのテーブルを作成します。
  • Customers テーブルの CustomerId 列は主キーです。
  • Orders テーブルの CustomerId 列は外部キーであり、Customers



using System;
using System.Data.SQLite;

namespace CreateForeignKeyRelationship
{
    class Program
    {
        static void Main(string[] args)
        {
            // データベース接続文字列
            string connectionString = @"Data Source=MyDatabase.sdf";

            // テーブル作成
            CreateTable(connectionString);

            // 外部キー関係作成
            CreateForeignKeyRelationship(connectionString);

            // データ挿入
            InsertData(connectionString);

            // データ読み取り
            ReadData(connectionString);
        }

        static void CreateTable(string connectionString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                string sql = @"
                    CREATE TABLE Customers (
                        CustomerId INTEGER PRIMARY KEY AUTOINCREMENT,
                        FirstName TEXT,
                        LastName TEXT
                    );

                    CREATE TABLE Orders (
                        OrderId INTEGER PRIMARY KEY AUTOINCREMENT,
                        CustomerId INTEGER,
                        OrderDate DATETIME,
                        FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)
                    );
                ";

                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }

        static void CreateForeignKeyRelationship(string connectionString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                string sql = @"
                    ALTER TABLE Orders
                    ADD FOREIGN KEY (CustomerId)
                    REFERENCES Customers(CustomerId)
                ";

                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }

        static void InsertData(string connectionString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                string sql = @"
                    INSERT INTO Customers (FirstName, LastName)
                    VALUES ('John', 'Doe'), ('Jane', 'Doe');

                    INSERT INTO Orders (CustomerId, OrderDate)
                    VALUES (1, '2023-01-01'), (2, '2023-02-01');
                ";

                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    command.ExecuteNonQuery();
                }
            }
        }

        static void ReadData(string connectionString)
        {
            using (SQLiteConnection connection = new SQLiteConnection(connectionString))
            {
                connection.Open();

                string sql = @"
                    SELECT 
                        c.FirstName, 
                        c.LastName, 
                        o.OrderDate
                    FROM Customers c
                    INNER JOIN Orders o ON c.CustomerId = o.CustomerId;
                ";

                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    using (SQLiteDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Console.WriteLine("{0} {1} - {2}", reader["FirstName"], reader["LastName"], reader["OrderDate"]);
                        }
                    }
                }
            }
        }
    }
}
  1. コードは、Customers テーブルと Orders テーブルにデータを追加します。

実行方法

  1. Program.cs ファイルに上記のコードを追加します。

出力

John Doe - 2023-01-01
Jane Doe - 2023-02-01

補足

  • このコードは、SQL Server CE 4.0 で動作します。
  • 詳細については、



SQL Server CE で外部キー関係を作成する他の方法

SQL Server Management Studio (SSMS) を使用する

SSMS は、SQL Server データベースを管理するためのツールです。SSMS を使用して外部キー関係を作成するには、次の手順に従います。

  1. SSMS を起動し、SQL Server CE データベースに接続します。
  2. オブジェクトエクスプローラーで、テーブル フォルダーを展開します。
  3. 外部キー関係を作成するテーブルを選択します。
  4. デザイナー タブをクリックします。
  5. 関係 ウィンドウで、新しい関係 をクリックします。
  6. 主キーテーブル ドロップダウンリストから、外部キーが参照するテーブルを選択します。
  7. OK をクリックします。

T-SQL を使用する

ALTER TABLE Orders
ADD FOREIGN KEY (CustomerId)
REFERENCES Customers(CustomerId)

Visual Studio には、データベースを操作するためのツールがいくつか含まれています。これらのツールを使用して外部キー関係を作成するには、次の手順に従います。

  1. Visual Studio で、データベースプロジェクトを開きます。
  2. プロパティ ウィンドウを開きます。
  3. 関係 プロパティページを選択します。

どの方法を使用しても、同じ結果が得られます。自分に最も適した方法を選択してください。


database visual-studio sql-server-ce


ファイルストレージの選択肢:クラウドストレージ、NoSQLデータベース、オブジェクトストレージ

利点:シンプルで使いやすいファイルへのアクセスが高速多くの種類のファイルを保存できるデータの整合性を保つのが難しいデータのバックアップと復元が難しいデータのセキュリティを確保するのが難しいデータの検索と分析が難しいファイルシステムよりも複雑...


C++でSQLiteデータベースを操作する:使いやすいオブジェクト指向ラッパー

OOラッパーは、SQLiteのC言語APIを抽象化し、C++開発者がより簡単にデータベース操作を行えるようにします。今回は、C++でSQLiteデータベースを操作する際に役立つ、おすすめのOOラッパーをいくつかご紹介します。SQLiteCpp:...


SELECT COUNT(1) vs INFORMATION_SCHEMA:テーブルのレコード数を取得する最適な方法は?

SELECT COUNT(1) FROM table_nameは、指定されたテーブル内のレコード数を取得するSQLクエリです。これは、テーブル全体にあるデータの量を把握したい場合に役立ちます。詳細解説SELECT COUNT(1):COUNT(1)は、テーブル内のレコード数をカウントする関数です。1を指定するのは、カウント対象となる列を明確にするためです。...


データベースの常識を変える! テンポラルデータベースが拓く革新的なアプリケーションの世界

テンポラルデータベースが必要となる理由はいくつかあります。以下に、その主な理由をいくつか紹介します。履歴データの追跡: テンポラルデータベースを使用すると、過去のデータの状態を簡単に追跡できます。これは、顧客レコード、医療記録、財務データなど、時間の経過とともに変化するデータを扱うアプリケーションにとって重要です。...


PostgreSQLデータベース作成:コマンドライン操作をマスターしよう

createdb コマンドは、PostgreSQL でデータベースを作成するための最も簡単な方法です。例えば、mydb という名前のデータベースを作成するには、次のようにコマンドを実行します。オプション-O 所有者名: データベースの所有者を指定します。...


SQL SQL SQL SQL Amazon で見る



CREATE TABLEステートメントのWITHオプションを使って外部キーを作成する

SQL Serverで外部キーを作成するには、以下の方法があります。T-SQL を使用して外部キーを作成するSQL Server Management Studio (SSMS) を起動し、データベースに接続します。オブジェクト エクスプローラー で、子テーブルを選択します。