【问题标题】:Preventing duplicate entry in database before inserting value into database在将值插入数据库之前防止数据库中的重复条目
【发布时间】:2017-08-14 22:57:02
【问题描述】:

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

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);

        }

【问题讨论】:

    标签: mysql cordova mobile duplicates sql-insert


    【解决方案1】:

    我认为您需要做的就是在 activityName 上建立一个唯一键...

    alter table dataEntryTb add unique key (activityName);
    

    【讨论】:

    • 我必须在哪里放线?
    • 它正在更改您的表定义...您可以在界面中输入(即 MySQL 命令行客户端、MySQL 工作台、toad 等...)该规则将在未来强制执行 - activityName不会重复。
    • 如果你有 dup... 你需要删除它们... 见stackoverflow.com/questions/2861594/…
    • 但是当我创建表时活动名称不是唯一的,它已经防止重复发生它只是我想给用户一个错误,以便他们知道为什么他们无法输入值跨度>
    • 你是对的——唯一约束和唯一键是一回事。当尝试重复值时,您应该会收到错误 - 问题是如何处理错误。我不知道这是否有帮助...stackoverflow.com/questions/18775493/…
    猜你喜欢
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多