今天我使用SQLite併發送一個帶有項目的數據庫文件。SQLite - 實時創建和更改數據庫
但是我想在用戶第一次啓動軟件時創建數據庫。
有沒有辦法根據現有的數據庫複製創建數據庫所需的代碼?問題是當用戶下載一個新版本時,他可能會被騙入他的最後一個數據庫並丟失數據。我想要一個很好的方法來檢查數據庫的版本並修改它,如果我需要新的列或表等。或者,如果它根本不存在,創建一個新的數據庫?
我知道我大概可以創建從一開始就創建數據庫的代碼,但我希望它是基於gui創建的現有數據庫。
已回答。最終代碼:
//Copy the database from the resource
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("resourcename"))
{
if (stream == null)
throw new NullReferenceException("Stream is null. Cannot find the database in the resources");
FileStream writer = new FileStream(Constants.SqLiteFile, FileMode.Create);
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = stream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writer.Write(buffer, 0, bytesRead);
bytesRead = stream.Read(buffer, 0, Length);
}
stream.Close();
writer.Close();
}
太棒了!好主意,感謝您的查詢,最有幫助。有些擔心:我希望能夠在沒有數據庫的情況下運送我的軟件。這意味着我沒有要比較的數據庫,我不能使用您提供的代碼創建數據庫。我想也許嵌入數據庫作爲資源(這是可能的),然後將其複製到本地,如果不存在。然後我可以與它比較。是否有可能將數據庫作爲資源? – 2010-04-15 17:43:57
確定你可以,嵌入它,然後你可以讀取它像這樣的指令:GetType()。Assembly.GetManifestResourceStream(「name of resource」); – 2010-04-15 18:31:56
不要忘記將編譯操作置於「嵌入式資源」 – 2010-04-15 18:32:59