0

我遇到了一些麻烦,我希望有人可以提供帮助。

我需要获取刚刚插入的数据库记录的 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 未定义

任何帮助,将不胜感激

提前致谢

麦克

4

1 回答 1

0

在插入后直接调用另一个 sql 语句来获取最大 ID,这不是最想要的方式,而是我可以让它工作的唯一方式。

于 2012-04-12T07:32:17.993 回答