1.新建數據庫java
DEMODB = openDatabase( shortName, //數據庫名,瀏覽器和SQL語句中會用到 version, //openDatabase 的版本,用1.0就能夠了 displayName, //數據庫顯示的全名/描述 maxSize //數據庫指望的上限體積大小 );
2.執行方法sql
DEMODB.transaction( function (transaction) { transaction.executeSql(sql, [參數]argument, 回調函數callback, 錯誤處理errorCallback); } );
3.處理返回集數據庫
function callback(transaction, results){ for (var i=0; i<results.rows.length; i++) { var row = results.rows.item(i);//row爲每一行 xx=row['colName'];//colName爲字段名 } }
demo:瀏覽器
1.初始化數據庫後,新建一張表添加默認數據。函數
/** *初始化數據庫 */ function initDatabase() { try { if (!window.openDatabase) {//先檢測一下瀏覽器是否支持這個方法,若是不支持進行提示 alert('Databases are not supported in this browser.'); } else {不然建立數據庫 var shortName = 'DEMODB'; var version = '1.0'; var displayName = 'DEMO Database'; var maxSize = 100000; // bytes DEMODB = openDatabase(shortName, version, displayName, maxSize); createTables();//建立表結構 selectAll();//查詢全部值 } } catch(e) {//異常處理 if (e == 2) { // Version number mismatch. console.log("Invalid database version."); } else { console.log("Unknown error "+e+"."); } return; } }
function createTables(){ DEMODB.transaction( function (transaction) { transaction.executeSql('CREATE TABLE IF NOT EXISTS demodb(id INTEGER NOT NULL PRIMARY KEY, name TEXT NOT NULL,password TEXT NOT NULL);', [], nullDataHandler, errorHandler); } ); insertData();//添加數據 } //添加數據 function insertData(){ DEMODB.transaction( function (transaction) { var data = ['1','hello','word']; transaction.executeSql("INSERT INTO demo(id,name, password) VALUES (?, ?, ?, ?, ?)" , [data[0], data[1], data[2]); } ); }
2.查詢數據this
function selectAll(){ DEMODB.transaction( function (transaction) { transaction.executeSql("SELECT * FROM demodb;", [],callbackHandler, errorHandler); } ); } function callbackHandler(transaction, results){ for (var i=0; i<results.rows.length; i++) { var row = results.rows.item(i); var newFeature = new Object(); name = row['name']; password = row['password']; document.getElementById("test").value=name; } }
參考自:http://www.oschina.net/question/12_26204.net