SQLite初始化的位置? (IOS)

时间:2018-01-27 12:04:07

标签: ios database sqlite

我正在为开源iOS应用做贡献,我需要在首次初始化时将行插入SQLite数据库。但由于我没有任何SQL经验,我不知道我应该在哪个文件中执行此操作,因此我一直在查看该项目几个小时,以找到传入数据的位置,但没有成功。这是我尝试添加行的表。我需要总共4行,名称为avatar_clothes_01(已经存在),avatar_clothes_02,avatar_clothes_03和avatar_clothes_04。非常感谢提前!

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个

  

数据库队列定义

/**
 Database Queue object.
 */
var oDatabaseQueue : FMDatabaseQueue;
  

初始部分

init() {

    let oDirPaths     = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true);
    let sDocsDir      = oDirPaths[0];
    let oDatabasePath = sDocsDir.stringByAppendingPathComponent("databaseName" + ".db");
    self.oDatabase    = FMDatabase(path: oDatabasePath as String);
    self.oDatabaseQueue = FMDatabaseQueue(path: oDatabasePath as String);
}
  

如果您将模型作为参数传递并根据

调整参数,那么插入数据库应该会更好
func insertTest(id:Int,name:String,points:Int,purchased:Bool){
        self.oDatabaseQueue.inDatabase() { oDatabase in

            if (oDatabase?.open())! {

                var sSql = "INSERT INTO Clothes (";
                sSql = sSql + "ID,";
                sSql = sSql + "Name,";
                sSql = sSql + "Points,";
                sSql = sSql + "Purchased";
                sSql = sSql + ") VALUES (";
                sSql = sSql + "?,";
                sSql = sSql + "?,";
                sSql = sSql + "?,";
                sSql = sSql + "?";
                sSql = sSql + ")";
                Int(purchased)
                let oArguments : [Any] = [
                    id,
                    name,
                    points,
                    Int(purchased)
                ];

                if (database!.executeUpdate(sSql, withArgumentsIn: oArguments)) {

                    database!.commit()
                }
            }
        }
}