2013-11-26 25 views
0

我正在嘗試使用C#& MySql爲了複製一個空表(重新創建Schema)。該結構是這樣的:如何使用C#複製MySql數據庫模式?

> TableTemplate (schema) 
    + Tables 
     > FirstTable (table) 
     > second table (table) 
     > ... 

> SomeOtherTable 
    + Tables 
     > ... 

我想什麼是對TableTemplate複製到與用戶名的新模式。

第一個明顯的遺忘路徑是嘗試CREATE TABLE @UserName LIKE TableTemplate,迅速得知sql參數應該用於值而不是表名(所有的hail jon雙向遊戲,同樣是:How to pass a table as parameter to MySqlCommand?)。

這樣我們就可以通過手動驗證用戶名來建立表名(robert's a prime example)。

接下來,似乎即使CREATE TABLE UserID LIKE TableTemplate;也不會工作(即使來自MySQL Workbench),因爲TableTemplate不是表格。

所以它的下跌編寫一個循環,將在TableTemplate創建一個表LIKE每個表,創建UserID架構後(該字符串的人工確認後),或嘗試其他選項,如反傾銷數據庫,並創建一個新的,因爲看到這些問題:

但我寧願避免運行的進程,轉儲數據庫,並在每次添加用戶時從那裏創建數據庫。

任何建議將不勝感激。

回答

1

結束了使用這樣的事情,在aName傳遞表名的方法:

using (MySqlCommand cmd = new MySqlCommand(string.Format("CREATE DATABASE {0} ;", aName), connection)) 
{ 
    cmd.ExecuteNonQuery();   // Create the database with the given user name 

    // Building the sql query that will return a "create table" per table in some_db template DB. 
    cmd.CommandText = (string.Format("SELECT CONCAT (\"CREATE TABLE {0}.\", TABLE_NAME ,\" " 
             + "LIKE some_other_db.\", TABLE_NAME) as creation_sql " 
             + "FROM information_schema.TABLES WHERE TABLE_SCHEMA = 'some_db';" 
            , aName)); 

    try  // Building the inner tables "create table" sql strings 
    { 
     using (MySqlDataReader reader = cmd.ExecuteReader()) 
     { 
      while (reader.Read()) 
       createInnerTablesList.Add(reader.GetString(0)); 
     } 
    } 
    catch (MySqlException mysql_ex) { ... } // handle errors 

    foreach (var sql_insert_query in createInnerTablesList) 
    { 
     try       // Insert the tables into the user database 
     { 
      cmd.CommandText = sql_insert_query; 
      cmd.ExecuteNonQuery(); 
     } 
     catch (Exception e) { ... } // handle errors 
    } 
} 

使用LIKE VS AS喜歡的原因Jungsu建議,即使AS將創建表格,它也不會保留定義的任何約束和鍵(主鍵等)。使用LIKE將使用約束條件複製它們。

我還是不太高興這一點,因爲我覺得我失去了一些東西,但...

1

我認爲mysqldump會更好。但如果你想在一個過程中完成。嘗試這個。

SELECT 
    CONCAT ("CREATE TABLE SomeOtherTable.", 
     TABLE_NAME ," AS SELECT * FROM TableTemplate.", TABLE_NAME 
    ) as creation_sql 
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'TableTemplate'; 

的輸出將是像

CREATE TABLE SomeOtherTable.tbl_name AS SELECT * FROM TableTemplate.tbl_name;

然後迭代結果和執行CREATE TABLE ....

+0

Upvoted,並增加了對我工作的答案。儘管如此,感謝您的幫助。 – Noctis

相關問題