Swift--创建数据库文件以及创建表和字段

    //在沙盒Document文件夹下,创建sqlit文件--- 下一步就是要在里面添加各种表了
    func setupLiveDataBase(){
    
    
        let doucumentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString
        let databasePath = doucumentPath.appendingPathComponent(liveDataBase)
        DBQueue = try! DatabaseQueue(path: databasePath)
        DBQueue.setupMemoryManagement(in: UIApplication.shared)
        print("\(databasePath)")

        DBPool = try! DatabasePool(path: databasePath) //document中创建了数据库,现在数据库里面没有一张表
        DBPool.setupMemoryManagement(in: UIApplication.shared)
        
        updateColumn()
    }
    
    //如果数据库没有axPersion这张表,就创建新的axPersion表在里面
    func updateColumn() {
    
    
        try! DBPool.write {
    
     db in
            do{
    
    
                if let _ = try String.fetchOne(db, "select sql from sqlite_master where tbl_name = 'axPersion' and type = 'table'") {
    
    
                
                } else {
    
    
                    try db.execute(
                        """
                        CREATE TABLE IF NOT EXISTS axPersion (
                        axPersionID integer PRIMARY KEY NOT NULL,
                        GlobalID text UNIQUE NOT NULL,
                        Name text UNIQUE NOT NULL,
                        Sex boolean NOT NULL DEFAULT(1),
                        Home text UNIQUE NOT NULL,
                        Age integer NOT NULL DEFAULT(0)
                        )
                        """
                    )
                }
            }catch let error as DatabaseError {
    
    
                print(error.description)
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/SoftwareDoger/article/details/103559153