我正在使用C#和xamarin工作室。我找不到一个工作示例来对我的数据库执行更新语句。我正在尝试将记录的值从50更新为100。
此类表示db中的一条记录:
[Table("record")]
public class Record
{
[PrimaryKey, AutoIncrementAttribute, Column("id")]
public int ID {get; set;}
[Column("value")]
public string Value {get; set;}
}
我可以使用以下方法检索我的记录:
string pathToDatabase = "mydb.db";
var db = new SqliteConnection (pathToDatabase);
myRecords = db.Query<Record>("SELECT * FROM records;");
更新应该像获取然后更新一样简单。
var recToUpdate = db.Get<Record>(1); // record with primary key of 1.
recToUpdate.Value = "100"; // instead of 50
db.Update(recToUpdate);
它执行更新行正常,但当我再次运行应用程序时,数据库仍然保持旧值50而不是100。
我的做法完全错了吗?
答案 0 :(得分:0)
尝试
recToUpdate.Value = "100"; // instead of 50
int i = db.Update(recToUpdate);
//check number of rows updated (i), db.Update() returns number of rows updated...
//or first try with recToUpdate.Value = 100; and see the number of rows affected + use try/catch if an error appears.
答案 1 :(得分:0)
如果您在应用包中包含现有数据库,则无法写入。应用程序包是只读的 - 这是iOS安全措施。为了写入您的数据库,您需要将其移动到用户可写文件夹。
// in your app startup
string rootPath = "/mydb.db";
string userPath = Path.Combine(Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "mydb.db";
// if userdb does not exist, copy it from the app bundle
if (!File.Exists(userPath)) {
File.Copy(rootPath, userPath);
}
当您想要实际访问数据库时,只需使用已有的数据库访问代码,但请确保使用用户可写路径。
var db = new SqliteConnection (userPath);
最后,如果您的数据库是只读的并且用户不会更新,您可以将其保留在应用程序包中,而不需要制作可写副本。