【发布时间】:2010-04-15 16:00:56
【问题描述】:
今天我使用 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();
}
【问题讨论】: