无法插入sqlite3 swift

时间:2017-10-24 05:10:36

标签: swift sqlite

尝试插入sqlite_sequence时显示语法错误

func CreateClientSequence(db:OpaquePointer?)
{

    let now = UInt64(NSDate().timeIntervalSince1970)


    if sqlite3_exec(db,"insert into sqlite_sequence (name,seq) values ('Customer',\(now)", nil, nil, nil) != SQLITE_OK {
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("error inserting table: \(errmsg)")
        print(now)
    }

    if sqlite3_finalize(statement) != SQLITE_OK {
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("error finalizing prepared statement: \(errmsg)")
    }

    statement = nil

}

并且尝试准备两者都不起作用

func CreateClientSequence(db:OpaquePointer?)
{

    let now = UInt64(NSDate().timeIntervalSince1970)

    if sqlite3_prepare_v2(db,"insert into sqlite_sequence (name,seq) values (?,?)", -1, &statement, nil) != SQLITE_OK {
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("error creating table: \(errmsg)")
                }

    if sqlite3_bind_text(statement, 2, "Customer", -1, SQLITE_TRANSIENT) != SQLITE_OK {
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("failure binding foo: \(errmsg)")
    }
    if sqlite3_bind_int64(statement, 1, now) != SQLITE_OK {
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("failure binding foo: \(errmsg)")
    }


    if sqlite3_finalize(statement) != SQLITE_OK {
        let errmsg = String(cString: sqlite3_errmsg(db)!)
        print("error finalizing prepared statement: \(errmsg)")
    }

    statement = nil

}

错误是"错误插入表:附近" 1508821343":语法错误"

1 个答案:

答案 0 :(得分:0)

几个问题:

  1. 您在第一个SQL中缺少右括号:

    if sqlite3_exec(db,"insert into sqlite_sequence (name,seq) values ('Customer',\(now))", nil, nil, nil) != SQLITE_OK { ... }
    

    您有)结束now的字符串插值,但不是values SQL的字符串插值。

  2. 在您第一次尝试时,您正在执行sqlite3_exec,在这种情况下sqlite3_finalize不仅不需要,而且不正确。

  3. 在第二个示例中,您永远不会调用sqlite3_step来执行预准备语句。完成装订后,但在最终确定之前完成。