Web Sql database 本機資料庫

來源:互聯網
上載者:User

標籤:

/* ** 介紹Web Sql Database使用 *///web sql database 資料庫入口function WebDatabase() {};(function() {    /**     *@decription 如果資料庫不存在,則建立      *@param {String} 資料庫名稱     *@param {String} 版本號碼     *@param {String} 資料庫描述     *@param {Number} 資料庫大小     *@param {Function} 回呼函數     */    var currentDb;    return WebDatabase.prototype = {        getCurrentDb: getCurrentDb,        openDb: openDb,        createTable: createTable,        insert: insert,        query: query,        update: update,        deleteItem: deleteItem,        dropTable: dropTable,        manualTransaction: manualTransaction    }    /**     * @param  {Object}     * name {String} 資料庫名稱     * version {String} 資料庫版本號碼     * desc {String} 資料庫的描述     * capacity {Number} 資料庫容量     * callback {Function} 建立或者開啟資料庫成功的回調     * @return {Object} 建立或者開啟的資料庫物件     */    function openDb(options) {        var defaultOptions = {                name: ‘‘,                version: ‘1.0‘,                desc: ‘‘,                capacity: 1024 * 1024,                callback: function() {}            },            optionsValue;        options = merge(options, defaultOptions);        optionsValue = getValues(options);        currentDb = openDatabase.apply(null, optionsValue);        return currentDb;    }    /**     *@param {String} 建立的sql語句     *@param {Array} 插入到查詢中問號所在處的字串資料     *@param {Function} 成功的回呼函數     *@param {Function} 失敗的回呼函數     */    // function executeSql(sql, [], success, fail){    //資料表操作    // }    function matchSql(sql, tableName) {        var reg = /\{\{(\w+)\}\}$/;        sql = sql.replace(reg, function(match, set) {            return tableName;        });        return sql;    }    /**    * @description 建立資料表    * @param {String} tableName 要建立的資料表名稱    * @param {Object} options 描述欄位    * @param {Function} success 成功的回調    * @param {Function} fail 執行失敗的回調    * @return {Undefined} 不返回結果    * @example    * createTable(‘student‘,{id:‘INTEGER UNIQUE PRIMARY KEY‘,name:‘TEXT‘})    * -----------------------    * id        | name     * -----------------------     */    function createTable(tableName, options, success, fail) {        var sql = ‘create table if not exists ‘ + tableName + ‘ (‘ + mergeArrToStr(options, ‘ ‘) + ‘)‘,            success = success || function() {                alert(‘success to create a table ‘ + tableName);            },            fail = fail || function() {                alert(‘fail to create a table ‘ + tableName)            };        sql = matchSql(sql, tableName);        console.log(sql);        currentDb.transaction(function(tx) {            tx.executeSql(sql, [], success, fail);        });    }    /**     * @param {String} tableName 要建立的資料表名稱     * @param  {Object} data 插入的資料欄位     * @param {Function} success 成功的回調     * @param {Function} fail 執行失敗的回調     * @return {Undefined} 無返回結果     * @example     * insert(‘student‘,{id:1,name:‘author‘})     * -----------------------     * id        | name      * 1 | author     * -----------------------      */    function insert(tableName, data, success, fail) {        var keys = getKeys(data).join(),            values = getValues(data),            qMark = values.map(function() {                return ‘?‘;            }),            sql = ‘insert into ‘ + tableName + ‘ (‘ + keys + ") values(" + qMark.join() + ")",            success = success || function() {                alert(‘success to insert a item to ‘ + tableName)            },            fail = fail || function() {                alert(‘fail to insert a item to ‘ + tableName)            };        sql = matchSql(sql, tableName);        console.log(sql);        currentDb.transaction(function(tx) {            tx.executeSql(sql, values, success, fail);        });    }    /**     * @param {String} tableName 要建立的資料表名稱     * @param  {Array} options 要查詢的欄位     * @param {Function} success 成功的回調     * @param {Function} fail 執行失敗的回調     * @return {Undefined} 無返回結果     * @example     * query(‘student‘,‘id‘)     * -----------     * id             * 1      * -----------     */    function query(tableName, options, success, fail) {    Array.isArray(options) ? ‘‘ : options=[options];        var keys = options ? options.join() : ‘*‘,            sql = ‘select ‘ + keys + ‘from ‘ + tableName,            success = success || function(tx, resultSet) {                alert(‘success to query in ‘ + tableName);                var resultLen = resultSet.rows.length,                    i = 0,                    result = [];                for (; i < resultLen; i++) {                    result.push(resultSet.rows.item(i));                }                console.log(result);            },            fail = fail || function() {                alert(‘fail to query in ‘ + tableName);            };        sql = matchSql(sql, tableName);        console.log(sql);        currentDb.transaction(function(tx) {            tx.executeSql(sql, [], success, fail);        });    }    /**     * @param {String} tableName 要建立的資料表名稱     * @param  {Object} options 要更新的欄位以及對應的值     * @param  {Object} 要更新的尋找欄位[單條資料]     * @param {Function} success 成功的回調     * @param {Function} fail 執行失敗的回調     * @return {Undefined} 無返回結果     * @example     * update(‘student‘,{name:‘AUTHOR‘},{name:‘id‘,value:1})     * -----------------------     * id        | name      * 1 | AUTHOR     * -----------------------       */    function update(tableName, options, where, success, fail) {        var updateStr, fail, success, sql, keys, values, qMark;        fail = fail || function() {                alert(‘fail to update the ‘ + tableName);            },            success = success || function() {                alert(‘success to update the ‘ + tableName);                console.log(arguments);            },            keys = getKeys(options);        values = getValues(options);        qMark = keys.map(function() {            return ‘?‘;        });        options = {};        keys.forEach(function(key, index) {            options[key] = qMark[index];        });        values.push(where.value);        updateStr = mergeArrToStr(options, ‘=‘),            sql = ‘update ‘ + tableName + ‘ set ‘ + updateStr + ‘ where ‘ + where.name + ‘= ? ‘;        sql = matchSql(sql, tableName);        console.log(sql);        currentDb.transaction(function(tx) {            tx.executeSql(sql, values, success, fail);        });    }    /**     * @param {String} tableName 要建立的資料表名稱     * @param  {Object} 要刪除的尋找欄位[單條資料]     * @param {Function} success 成功的回調     * @param {Function} fail 執行失敗的回調     * @return {Undefined} 無返回結果     * @example     * deleteItem(‘student‘,{name:‘id‘,value:1})     * -----------------------     * id        | name      * -----------------------      */    function deleteItem(tableName, where, success, fail) {        var sql = ‘delete from ‘ + tableName + ‘ where ‘ + where.name + ‘= ?‘,            success = success || function(tx, resultSet) {                alert(‘success to delete a item in ‘ + tableName);                var len = resultSet.rows.length,                    i = 0,                    result = [];                for (; i < len; i++) {                    result.push(resultSet.rows.item(i));                }                console.log(resultSet.rowsAffected);            },            fail = fail || function() {                alert(‘fail to delete a item in ‘ + tableName)            };        sql = matchSql(sql, tableName);        console.log(sql);        currentDb.transaction(function(tx) {            tx.executeSql(sql, [where.value], success, fail);        });    }    /**     * @param  {String} tableName 要刪除的資料表名稱     * @param  {Function} 刪除成功的回調     * @param  {Function} 刪除失敗後的回調     * @return {Undefined} 無返回結果     * @example     * dropTable(‘student‘)     * -------------------     * -------------------     */    function dropTable(tableName, success, fail) {        var sql = ‘drop table ‘ + tableName,            success = success || function() {                console.log(‘dropTable:‘, arguments);            },            fail = fail || function() {};        sql = matchSql(sql, tableName);        console.log(sql);        currentDb.transaction(function(tx) {            tx.executeSql(sql, [], success, fail);        });    }    /**     * @description 自己手動執行的sql     * @param  {String} sql語句     * @param  {Array||String} 需要的資料     * @param  {Function} 成功執行後的回調     * @param  {Function} 執行失敗的回調     * @return {Undefined} 無返回結果     * @example     * var sql = ‘create table if not exists student (id INTEGER NOT NULL PRIMARY KEY,name TEXT)‘; * manualTransaction(sql); * ----------------------- * id    | name * -----------------------     */    function manualTransaction(sql, values, success, fail) {        values = Array.isArray(values) ? values : [values];        currentDb.transaction(function(tx) {            tx.executeSql(sql, values, success, fail);        });    }    /**     * @return {Object} 當前的活動資料庫     */    function getCurrentDb() {        return currentDb;    }    function merge(target, source) {        var result = {};        for (var i in source) {            if (source.hasOwnProperty(i)) {                result[i] = target[i] || source[i];            }        }        return result;    }    function getValues(obj) {        var keys = getKeys(obj),            length = keys.length,            values = [];        for (var i = 0; i < length; i++) {            values[i] = obj[keys[i]];        }        return values;    }    function getKeys(obj) {        if (typeof obj !== ‘object‘) return [];        return Object.keys(obj);    }    function mergeArrToStr(options, connector) {        var keys = getKeys(options),            values = getValues(options),            updateStr;        updateStr = keys.map(function(value, index) {            return value + connector + values[index];        });        return updateStr.join();    }})();

  使用本地的資料庫管理系統實現資料的管理:

使用方法:

var localDb = new WebDatabase();localDb.openDb();

  

 

Web Sql database 本機資料庫

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.