I am new to SQL, but I am trying to set up a database in the html5 sql storage using a javascript in a jquery $(document).ready statement. I have been testing in Chrome, and firefox, but firefox does not work at all, and the problem that I have in chrome, is that I can set up a d开发者_开发知识库efault value just fine if it is a static value, but when I try to use a function, things do not turn out so well, I think that this code only calls the default function once when I actually want it to call the function every time. However, when I try to do that the function ErrorDB gets called. here is the code:
$(document).ready(function()
{
var db;
try{if(window.openDatabase){
db =openDatabase("fetchnotes", "1.0","fetchnotesDB",1000000);
if (!db) {alert("failed to load database on disk"); return;};
}
else{
alert("could not open database.");
return;
}
}catch(err){alert("error "+err); return;}
db.transaction(initializeDB, errorDB);
});
function initializeDB(tx){
tx.executeSql('Drop TABLE IF EXISTS NOTES');
tx.executeSql('CREATE TABLE IF NOT EXISTS'+
' NOTES(ID int primary key,NoteText, LastModified Date NOT NULL DEFAULT "'
+defaultLastModified()+ '")');
tx.executeSql('INSERT INTO NOTES (ID, NoteText) VALUES (1, "make a better database") ');
}
function errorDB(tx,err)
{
alert("error "+err);
}
function defaultLastModified()
{
var result= new Date();
return result;
}
Okay I found something of a solution for the problem, which is that That I had an incorrect data type as well as a few other things. the for corrected code is here:
tx.executeSql("CREATE TABLE IF NOT EXISTS"+
" NOTES(ID INTEGER PRIMARY KEY,NoteText TEXT ," +
"LastModified TIMESTAMP DEFAULT (datetime('now','localtime')));");
you technically do not need the 'localtime', leaving it out means that the time would be in GMT which is standard for SQL. However, I still do not know how to in general get a user defined function to be the default value, which is still my main question.
There are 3 things I think are wrong.
- I'm pretty sure a JS Date-object won't fit in a SQL-query (
... "' + defaultLastModified() + "' ...
). - If it would fit, it wouldn't work as you think either:
defaultLastModified()
will returnnow
, so when you add a record in 2 weeks, it'll still containnow
(so 2 weeks prior to adding the record). - Haven't dates (in SQL) got a default value by default (that'll automatically fill in the real
now
, always)?
My understanding is that executeSql is only supported on WebKit based browsers, thus it will not work in Firefox or IE. I would suggest looking for another method to write to a browser side database.
For WebKit browsers (Chrome, Safari) you may want to try using a semicolon to close the SQL statement.
Example
tx.executeSql('CREATE TABLE IF NOT EXISTS NOTES(ID int primary key,NoteText, LastModified Date NOT NULL DEFAULT "' + defaultLastModified() + '");');
精彩评论