在将值插入数据库之前,防止在数据库中重复输入

时间:2017-03-22 17:04:54

标签: mysql cordova mobile duplicates sql-insert

我正在尝试检查数据库以查看我输入的活动名称是否已存在,如果存在我应该收到错误,如果不存在它应该继续并将值插入数据库,下面是代码我正在尝试但它不能正常工作btw防止重复已经工作因为UNIQUE KEY我给活动名称但我也想要一个警告让用户知道活动名称已经存在。

function insertQueryDB(tx) {
        var myDB = window.openDatabase("test", "1.0", "Test DB", 1000000);
        tx.executeSql('CREATE TABLE IF NOT EXISTS dataEntryTb (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, activityName TEXT NOT NULL UNIQUE, location TEXT NOT NULL, time NOT NULL, date NOT NULL, reporter NOT NULL)');
            var an = document.forms["myForm"]["activityName"].value;
            var l = document.forms["myForm"]["location"].value;
            var t = document.forms["myForm"]["time"].value;
            var d = document.forms["myForm"]["date"].value;
            var r = document.forms["myForm"]["reporter"].value;
            if('COUNT activityName FROM dataEntryTb WHERE EXISTS activityName = "'+an+'" '){
            navigator.notification.alert("activityName already Exists");
            }
            var query = 'INSERT INTO dataEntryTb ( activityName, location, time, date, reporter) VALUES ( "'+an+'", "'+l+'", "'+t+'", "'+d+'", "'+r+'")';
            tx.executeSql(query,[]);

            navigator.notification.alert("Retrieved the following: Activity Name="+an+" and Location="+l);

        }

1 个答案:

答案 0 :(得分:0)

我认为你需要做的就是在activityName上建立一个唯一的密钥......

alter table dataEntryTb add unique key (activityName);