Phonegap插入ID未定义

时间:2012-04-04 07:58:10

标签: cordova

我遇到了一点麻烦,我希望那里有一个可以提供帮助。

我需要获取刚刚插入的db记录的ID,以便我可以与其他表中的其他行进行FK连接。

CREATE TABLE IF NOT EXISTS [Jobs] ( "ID" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "SourceID" guid,"Version" integer DEFAULT 0, "IsActive" bit DEFAULT 1, "LastUpdated" datetime DEFAULT (CURRENT_TIMESTAMP), "JobGPSLocation" nvarchar(100) COLLATE NOCASE)


    Job.prototype.Insert = function () {
        "use strict";
        try {
            console.log('Started: Job.prototype.Insert');
            console.log('ID of item been inserted ' + this.SourceID);
            var sqlcmd = 'INSERT INTO Jobs(ID,';
            sqlcmd += 'SourceID,';
sqlcmd += 'JobGPSLocation,';
            sqlcmd += 'IsActive , LastUpdated, Version) VALUES ';
            sqlcmd += '(NULL,';
            sqlcmd += '"' + this.SourceID + '",';
            sqlcmd += '"' + MakeDBSafe(this.JobGPSLocation) + '",';
            sqlcmd += this.IsActive + ',';
            sqlcmd += '"' + DateToSqlite(this.LastUpdated) + '",';
            sqlcmd += this.Version;
            sqlcmd += ')';
            console.log('B4 ClientDB.Transaction ' + sqlcmd);
            if ((ClientDB !== null) && (loggeduser !== null)) {
                var tempobj = this;
                ClientDB.transaction(function (tx) { JobInsert(tx, sqlcmd, tempobj); }, JobprototypeInsertErrorHandler);
            }
            else {
                console.log('Error: Job.prototype.Insert -- ClientDB And/Or loggeduser is null');
            }
        }
        catch (e) {
            console.log('Error: Engineer.prototype.Insert' + e);
        }
        function JobInsert(tx, sqlcmd, objref) {
            console.log('Started: JobInsert');
            console.log(sqlcmd);
            tx.executeSql(sqlcmd, [],
            function (transaction, results) {
                objref.ID = results.insertId;
                console.log('JobInsert insertId ' + results.insertId);
                console.log('JobInsert rowAffected ' + results.rowAffected);
                console.log('JobInsert rows ' + results.rows);
                console.log('JobInsert rows count ' + results.rows.length);

                for (var i = 0; i < results.rows.length; i++) {
                    for (prop in results.rows) {
                        str += prop + " value :" + obj[prop] + "\n"; //Concate prop and its value from object
                    }
                }

            }, JobprototypeInsertErrorHandler);
            console.log('Finished: JobInsert');
            console.log('JobInsert ID after insert ' + objref.ID);
        }
        var JobprototypeInsertErrorHandler = function (transaction, error) {
            console.log('JobprototypeInsertErrorHandler -- ' + error);
        };
    };

但上面的代码总是返回

  

JobInsert insertId undefined

任何帮助将不胜感激

提前致谢

LMAC

1 个答案:

答案 0 :(得分:0)

调用另一个sql语句以在插入后直接获得最大id,而不是最理想的方式,但只有这样才能让它工作。