2017-01-24 42 views
2

我寫的,在MS SQL Server Express的2014年創建表的功能在這裏:我可以使用ADO.NET和C#在MS SQL Express 2014 LocalDB中創建表嗎?

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(21天試用版)的先決條件安裝的MS SQL Server Express LocalDB時,則不會創建表。 SQL Server類型(Express和Express LocalDB)有沒有原因?或者我在我的代碼中做了任何錯誤。您的幫助將受到高度讚賞。

+1

答案顯然是肯定的。你問來幹什麼?你有錯誤嗎?例外?什麼東西?發佈* full *異常消息,包括調用堆棧。你可以使用'Exception.ToString'獲得那個 –

+1

如果沒有錯誤,那麼你如何檢查丟失的表?你在連接字符串中使用DataDirectory嗎? – Steve

+0

我不在連接字符串中使用DataDirectory。 – Prohor

回答

0

是的,我們可以從C#直接創建表的ADO.NETSome more example or things to remember when you create it from backend

這裏是創建具有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."); 
    } 
} 
+0

Thanks.It很好。 – Prohor

+0

如果符合您的要求,您可以接受此答案。@ Prohor –

相關問題