· 10 years ago · Sep 16, 2016, 08:18 PM
1<html>
2<head>
3<title>Look at WebSQL</title>
4<script>
5 // Through the code below remember essentialy there are just 3 core methods we tend to use
6 // openDatabase
7 // transaction
8 // executeSql
9 // Opening a connection
10 // window.openDatabase( database name , version , database description, estimated size );
11 // The size is flexible but some browsers put a restriction of 5mb so know your environment
12 var db = window.openDatabase("myDatabase", "1.0", "My WebSQL test database", 5*1024*1024);
13 if(!db) {
14 // Test your DB was created
15 alert('Your DB was not created this time');
16 return false
17 }
18
19 // Prepare you statement
20 // With your DB working we can add tables and run queries via the transaction function
21 // db.transactions( transaction, error callback, ready callback )
22 db.transaction(
23 function(tx){
24 // Execute the SQL via a usually anonymous function
25 // tx.executeSql( SQL string, arrary of arguments, success callback function, failure callback function)
26 // To keep it simple I've added to functions below called onSuccessExecuteSql() and onFailureExecuteSql()
27 // to be used in the callbacks
28 tx.executeSql(
29 "CREATE TABLE IF NOT EXISTS fightclub (id INTEGER PRIMARY KEY AUTOINCREMENT, rules TEXT)",
30 [],
31 onSuccessExecuteSql,
32 onError
33 )
34 },
35 onError,
36 onReadyTransaction
37 )
38 // At this point you now know everything to continue. All I'm am going to do now is add
39 // a single record to our table
40 db.transaction(
41 function(tx){
42 tx.executeSql( "INSERT INTO fightclub(rules) VALUES(?)",
43 ['You do not talk about Fight Club'],
44 onSuccessExecuteSql,
45 onError )
46 },
47 onError,
48 onReadyTransaction
49 )
50
51 // All thats left is to get the results on the page
52 // There where clause below is weak, but its just an example of preparing your statement
53 db.transaction(
54 function(tx){
55 tx.executeSql( "SELECT * FROM fightclub WHERE id > ?",
56 ['0'],
57 displayResults,
58 onError )
59 },
60 onError,
61 onReadyTransaction
62 )
63
64 function onReadyTransaction( ){
65 console.log( 'Transaction completed' )
66 }
67 function onSuccessExecuteSql( tx, results ){
68 console.log( 'Execute SQL completed' )
69 }
70 function onError( err ){
71 console.log( err )
72 }
73 function displayResults( tx, results ){
74
75 if(results.rows.length == 0) {
76 alert("No records found");
77 return false;
78 }
79
80 var row = "";
81 for(var i=0; i<results.rows.length; i++) {
82 row += results.rows.item(i).rules + "<br/>";
83 }
84 document.body.innerHTML = row
85 }
86</script>
87
88</head>
89<body>
90
91</body>
92</html>