1. 程式人生 > >【解決方案】資料庫建立和重新建立

【解決方案】資料庫建立和重新建立

很多人在寫資料庫軟體的時候,並未考慮周全。其實無法考慮周全,總在寫的時候,有那麼一些靈感,讓你改動資料庫結構。當你的軟體完工的時候,發現與最初的設計已經面目全非啦。

在寫軟體過程中,資料庫被改爛的問題常常發生,問題是爛了之後怎麼恢復?這裡有一招: 在你的軟體中建立一個初始化環境的功能,這其中就包括建立資料庫。

靈感來了,修改了資料庫結構,馬上在你的初始化程式碼中修改:

List<String> tableList = new List<string>();
String tableString = @"
CREATE TABLE IF NOT EXISTS apis (
id INTEGER PRIMARY KEY AUTOINCREMENT, api_id INT DEFAULT (0), api_class CHAR (50), api_cmd CHAR (50), api_description TEXT)"; tableList.Add(tableString); //...... //所有的建立資料庫結構的SQL語句 //...... using (SQLiteConnection sQLiteConnection = new SQLiteConnection
(SQLiteConnectionString)) { sQLiteConnection.Open(); SQLiteCommand sQLiteCommand = new SQLiteCommand("", sQLiteConnection); foreach (String item in tableList) { sQLiteCommand.CommandText = item; sQLiteCommand.ExecuteNonQuery(); } }

這樣,你的軟體將不被現有的資料庫結構所限制,隨時可以初始化,而不在乎資料庫是否已經被你搞爛。

好啦,就到這裡,如果你有疑問,歡迎留言。