WebSQL - Exemplos
crud-offline - três exemplos usando o WebSQL
<html>
<head>
<title>Look at WebSQL</title>
<script>
//https://gist.github.com/andyj/1599544
// Through the code below remember essentialy there are just 3 core methods we tend to use
// openDatabase
// transaction
// executeSql
// Opening a connection
// window.openDatabase( database name , version , database description, estimated size );
// The size is flexible but some browsers put a restriction of 5mb so know your environment
var db = window.openDatabase("myDatabase", "1.0", "My WebSQL test database", 5*1024*1024);
if(!db) {
// Test your DB was created
alert('Your DB was not created this time');
return false
}
// Prepare you statement
// With your DB working we can add tables and run queries via the transaction function
// db.transactions( transaction, error callback, ready callback )
db.transaction(
function(tx){
// Execute the SQL via a usually anonymous function
// tx.executeSql( SQL string, arrary of arguments, success callback function, failure callback function)
// To keep it simple I've added to functions below called onSuccessExecuteSql() and onFailureExecuteSql()
// to be used in the callbacks
tx.executeSql(
"CREATE TABLE IF NOT EXISTS fightclub (id INTEGER PRIMARY KEY AUTOINCREMENT, rules TEXT)",
[],
onSuccessExecuteSql,
onError
)
},
onError,
onReadyTransaction
)
// At this point you now know everything to continue. All I'm am going to do now is add
// a single record to our table
db.transaction(
function(tx){
tx.executeSql( "INSERT INTO fightclub(rules) VALUES(?)",
['You do not talk about Fight Club'],
onSuccessExecuteSql,
onError )
},
onError,
onReadyTransaction
)
// All thats left is to get the results on the page
// There where clause below is weak, but its just an example of preparing your statement
db.transaction(
function(tx){
tx.executeSql( "SELECT * FROM fightclub WHERE id > ?",
['0'],
displayResults,
onError )
},
onError,
onReadyTransaction
)
function onReadyTransaction( ){
console.log( 'Transaction completed' )
}
function onSuccessExecuteSql( tx, results ){
console.log( 'Execute SQL completed' )
}
function onError( err ){
console.log( err )
}
function displayResults( tx, results ){
if(results.rows.length == 0) {
alert("No records found");
return false;
}
var row = "";
for(var i=0; i<results.rows.length; i++) {
row += results.rows.item(i).rules + "<br/>";
}
document.body.innerHTML = row
}
</script>
</head>
<body>
</body>
</html>
Comments fornecido por CComment