Замените элемент в базе данных webSQL новым элементом, если он имеет ту же дату

У меня есть поле ввода для заголовка и примечания, и дата создается автоматически на основе текущей даты. Однако я хотел бы, чтобы база данных обновлялась, так что если в базе данных уже есть элемент с сегодняшней датой, любой новый элемент с той же датой заменит его. Возможно ли это, или мне придется сделать несколько записей с одной и той же датой?

document.getElementById("hide").style.visibility = "hidden";
document.getElementById("enterBtn").addEventListener("click", addEntry);
document.getElementById("display").addEventListener("click", display);
document.getElementById("hide").addEventListener("click", hidden);
//document.getElementById("listDiv2").innerHTML = " ";

//var date = new Date();
//date = new Date(date).toUTCString();
//date = date.split(' ').slice(0, 5).join(' ');


if (window.openDatabase) {
    //Create the database the parameters are 1. the database name 2.version 
    number 3. a description 4. the size of the database( in bytes) 1024 x 1024 = 1 MB
    var mydb = openDatabase("wellness", "0.1", "Wellness App", 1024 * 1024);

    //create the entry table using SQL for the database using a transaction
    mydb.transaction(function(t) {
        t.executeSql("CREATE TABLE IF NOT EXISTS notes (id INTEGER PRIMARY 
            KEY ASC, v_date TEXT, title TEXT, note TEXT)
        ");
    });

} else {
    myApp.alert("init if statement error");
}


//function to output the list of entry in the database

function updateEntryList(transaction, results) {
    //initialise the listitems variable

    var listitems = " ";

    var listholder = document.getElementById("listDiv2");

    //clear entry list ul
    listholder.innerHTML = " ";

    var i;

    //Iterate through the results
    for (i = 0; i < results.rows.length; i++) {

        var row = results.rows.item(i);

        listholder.innerHTML += "<li>" + "<p>" + '<h2>' + '<u>' + row.title +
            '</u>' + '</h2>' + "<p>" + '<h3>' + 'Note: ' + row.note + '</h3>' + "<p>" +
            row.v_date + "<p>" + "__________________" + "</li>";
    }
}

function clearText() {
    //document.getElementById('v_date').value = '';
    document.getElementById('title').value = '';
    document.getElementById('note').value = '';
}

//function to get the list of entry from the database

function outputEntry() {
    //check to ensure the mydb object has been created
    if (mydb) {
        //Get all the entry from the database with a select statement, set 
        outputEntryList as the callback
        function
        for the executeSql command
        mydb.transaction(function(t) {
            t.executeSql("SELECT * FROM notes", [], updateEntryList);
            //myApp.alert("outputEntry called");
        });
    } else {
        myApp.alert("outputEntry error");
    }
}


function display() {
    outputEntry();
    document.getElementById("display").style.visibility = "hidden";
    document.getElementById("listDiv2").style.visibility = "visible";
    document.getElementById("hide").style.visibility = "visible";
}

function hidden() {
    document.getElementById("display").style.visibility = "visible";
    document.getElementById("listDiv2").style.visibility = "hidden";
    document.getElementById("hide").style.visibility = "hidden";
}
//function to add the car to the database

function addEntry() {
    //check to ensure the mydb object has been created
    if (mydb) {
        //myApp.alert("if statement good");
        //var d = new Date();
        //var date = d.toDateString();
        //get the values of the make and model text inputs
        //var v_date = document.getElementById("v_date").value;
        var title = document.getElementById("title").value;
        var note = document.getElementById("note").value;

        v_date = new Date;
        v_date = new Date(v_date).toUTCString();
        v_date = v_date.split(' ').slice(0, 4).join(' ')

        //date = new Date(date).toUTCString();
        //date = date.split(' ').slice(0, 5).join(' ');

        //myApp.alert("all elements got by id");

        //Test to ensure that the user has entered both a make and model
        if (title !== "" && note !== "") {

            //Insert the user entered details into the entry table, note the use 
            of the ? placeholder, these will replaced by the data passed in as an
            array as the second parameter
            mydb.transaction(function(t) {
                t.executeSql("INSERT INTO notes (v_date, title, note) VALUES (?, ?, ?)", [v_date, title, note]);

                myApp.alert("Your Entry Added");
            });
        } else {
            myApp.alert("You must enter values!");
        }

    } else {
        myApp.alert("add entry error");
    }
    clearText();
}

person Hugh O Dwyer    schedule 03.08.2017    source источник


Ответы (1)


Почему бы вам не использовать строку в качестве первичного ключа?

var date = new Date();
var key = date.getFullYear() + date.getMonth() + date.getDate()

и используйте этот ключ с INSERT OR REPLACE INTO

person kevinSpaceyIsKeyserSöze    schedule 03.08.2017