簡體   English   中英

我可以使用ADO.NET和C#在MS SQL Express 2014 LocalDB中創建表嗎?

[英]Can I create table in MS SQL Express 2014 LocalDB using ADO.NET and C#?

我編寫了一個在MS SQL Server Express 2014中創建表的函數。它是:

    private static void createAndAlterTables()
    {
        try
        {
            // Создать соединение с БД.
            using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnection"].ConnectionString))
            {
                try
                {
                    SqlCommand sqlCom = new SqlCommand();
                    sqlCom.Connection = sqlCon;
                    sqlCon.Open();
                    MessageBox.Show("Выполняется создание таблиц", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                    sqlCom.CommandText = @"CREATE TABLE [dbo].[AddedDevices](
                                          [Id] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
                                          [ProfileId] [uniqueidentifier] NULL,
                                          [MountingLocation] [nvarchar](max) NULL,
                                          [DeviceName] [nvarchar](50) NULL,
                                          [SerialNumber] [nvarchar](50) NULL,
                                          [DeviceDescription] [nvarchar](max) NULL,
                                          [OwnerCompany] [nvarchar](50) NULL,
                                          [StreetHouse] [nvarchar](max) NULL,
                                          [LocalityRegion] [nvarchar](max) NULL,
                                          [Country] [nvarchar](50) NULL,
                                          [ZipCode] [nvarchar](50) NULL,
                                          [SwHwVersion] [nvarchar](50) NULL,
                                          [DeviceType] [nvarchar](50) NULL,
                                          [SelectedInnerDiameter] [nvarchar](50) NULL,
                                          [SelectedBeamsQuantity] [nvarchar](50) NULL,
                                          [SelectedExClass] [nvarchar](50) NULL,
                                          [PathToStorageFolder] [nvarchar](max) NULL,
                                     CONSTRAINT [PK_AddedDevices] PRIMARY KEY CLUSTERED (
                                          [Id] ASC
                                       )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
                                     ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]";
                    sqlCom.ExecuteNonQuery();
                    MessageBox.Show("Таблица 'AddedDevices' успешно создана", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                    //
                    sqlCom.CommandText = @"ALTER TABLE [dbo].[AddedDevices] ADD  CONSTRAINT [DF_AddedDevices_Id]  DEFAULT (newid()) FOR [Id]";
                    sqlCom.ExecuteNonQuery();
                    MessageBox.Show("Таблица 'AddedDevices' успешно изменена", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                    //
                    sqlCom.CommandText = @"CREATE TABLE [dbo].[DeviceProfile](
                                          [Id] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
                                          [DeviceName] [nvarchar](100) NULL,
                                          [Brand] [nvarchar](50) NULL,
                                          [DisplayedName] [nvarchar](200) NULL,
                                          [RepositoryFileName] [nvarchar](200) NULL,
                                          [RegistersQuantity] [int] NULL,
                                          [DeviceTypeCode] [int] NULL,
                                          [SerialNumber] [nvarchar](100) NULL,
                                     CONSTRAINT [PK_DeviceProfile_Id] PRIMARY KEY CLUSTERED (
                                          [Id] ASC
                                       )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
                                     ) ON [PRIMARY]";
                    sqlCom.ExecuteNonQuery();
                    MessageBox.Show("Таблица 'DeviceProfile' успешно создана", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                    //
                    sqlCom.CommandText = @"ALTER TABLE [dbo].[DeviceProfile] ADD  CONSTRAINT [DF_DeviceProfile_Id]  DEFAULT (newid()) FOR [Id]";
                    sqlCom.ExecuteNonQuery();
                    MessageBox.Show("Таблица 'DeviceProfile' успешно изменена", "Сообщение", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                        MessageBox.Show(ex.InnerException.Message, "Ошибка при создании таблиц", MessageBoxButton.OK, MessageBoxImage.Error);
                    else
                        MessageBox.Show(ex.Message, "Ошибка при создании таблиц", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        catch (Exception ex)
        {
            // Если сбой транзакции:
            if (ex.InnerException != null)
                MessageBox.Show(ex.InnerException.Message, "Ошибка при создании таблиц", MessageBoxButton.OK, MessageBoxImage.Error);
            else
                MessageBox.Show(ex.Message, "Ошибка при создании таблиц", MessageBoxButton.OK, MessageBoxImage.Error);
        }
    }

當我連接到MS SQL Server Express 2014並嘗試創建表時,則結果成功。 但是,當我連接到從InstallShield 2016 Premier中的必備軟件安裝的MS SQL Server Express LocalDB(21天試用版)時,未創建表。 SQL Server類型(Express和Express LocalDB)是否存在原因? 或者我在代碼中做錯了什么。 非常感謝您的幫助。

是的,我們可以直接從C#ADO.NET創建表,請檢查一些其他示例或從后端創建表時要記住的事情

這是創建具有identity列的表的簡單示例:

private void btnDatabase_Click(object sender, EventArgs e)
{
    using (SqlConnection connection =
    new SqlConnection("Data Source=(local);" +
              "Database='Exercise1';" +
              "Integrated Security=yes;"))
    {
    SqlCommand command =
        new SqlCommand("CREATE TABLE StoreItems( " +
               "StoreItemID int IDENTITY(1, 1) NOT NULL, " +
               "Category varchar(50), " +
               "[Item Name] varchar(100) NOT NULL, " +
               "Size varchar(20), " +
               "[Unit Price] money);",
               connection);
    connection.Open();
    command.ExecuteNonQuery();

    MessageBox.Show("A new table named StoreItems has been crated.");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM