[转载]html5 local database

10 篇文章 0 订阅
8 篇文章 0 订阅

记录下来,以备查看

----------------------------------------------------------------

The Web SQL Database API isn't actually part of the HTML5 specification but it is a separate specification which introduces a set of APIs to manipulate client-side databases using SQL.

I'm assuming you are a great web developer and if that is the case then no doubt, you would be well aware of SQL and RDBMS concepts. If you still want to have a session with SQL then, you can go through our SQL Tutorial.

Web SQL Database will work in latest version of Safari, Chrome and Opera.

The Core Methods:

There are following three core methods defined in the spec that I.m going to cover in this tutorial:

  1. openDatabase: This method creates the database object either using existing database or creating new one.

  2. transaction: This method give us the ability to control a transaction and performing either commit or rollback based on the situation.

  3. executeSql: This method is used to execute actual SQL query.

Opening Database:

The openDatabase method takes care of opening a database if it already exists, this method will create it if it already does not exist.

To create and open a database, use the following code:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);

Above method took following five paramters:

  1. Database name
  2. Version number
  3. Text description
  4. Size of database
  5. Creation callback

The last and 5th argument, creation callback will be called if the database is being created. Without this feature, however, the databases are still being created on the fly and correctly versioned.

Executing queries:

To execute a query you use the database.transaction() function. This function needs a single argument, which is a function that takes care of actually executing the query as follows:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {  
   tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
});

The above query will create a table called LOGS in 'mydb' database.

INSERT Operation:

To create enteries into the table we add simple SQL query in the above example as follows:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
   tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});

We can pass dynamic values while creating entering as follows:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {  
  tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
  tx.executeSql('INSERT INTO LOGS 
                        (id,log) VALUES (?, ?'), [e_id, e_log];
});

Here e_id and e_log are external variables, and executeSql maps each item in the array argument to the "?"s.

READ Operation:

To read already existing records we use a callback to capture the results as follows:

var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
   tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
   tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});
db.transaction(function (tx) {
   tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
   var len = results.rows.length, i;
   msg = "<p>Found rows: " + len + "</p>";
   document.querySelector('#status').innerHTML +=  msg;
   for (i = 0; i < len; i++){
      alert(results.rows.item(i).log );
   }
 }, null);
});

/***********************************DEMO**************************************/

/*
Main JS for tutorial: "Getting Started with HTML5 Local Databases"
Written by Ben Lister (darkcrimson.com) revised 12 May 2010
Tutorial: http://blog.darkcrimson.com/2010/05/local-databases/

Licensed under the MIT License:
http://www.opensource.org/licenses/mit-license.php
*/

$(function(){ initDatabase();

 	// Button and link actions
	$('#clear').click(function(){ dropTables(); });
 	$('#update').click(function(){ updateSetting(); });

});
	
function initDatabase() {
	try {
	    if (!window.openDatabase) {
	        alert('Local Databases are not supported by your browser. Please use a Webkit browser for this demo');
	    } else {
	        var shortName = 'DEMODB';
	        var version = '1.0';
	        var displayName = 'DEMODB Test';
	        var maxSize = 100000; // in bytes
	        DEMODB = openDatabase(shortName, version, displayName, maxSize);
			createTables();
			selectAll();
	    }
	} catch(e) {
	    if (e == 2) {
	        // Version mismatch.
	        console.log("Invalid database version.");
	    } else {
	        console.log("Unknown error "+ e +".");
	    }
	    return;
	} 
}



/***
**** CREATE TABLE ** 
***/
function createTables(){
	DEMODB.transaction(
        function (transaction) {
        	transaction.executeSql('CREATE TABLE IF NOT EXISTS page_settings(id INTEGER NOT NULL PRIMARY KEY, fname TEXT NOT NULL,bgcolor TEXT NOT NULL, font TEXT, favcar TEXT);', [], nullDataHandler, errorHandler);
        }
    );
	prePopulate();
}


/***
**** INSERT INTO TABLE ** 
***/
function prePopulate(){
	DEMODB.transaction(
	    function (transaction) {
		//Starter data when page is initialized
		var data = ['1','none','#B3B4EF','Helvetica','Porsche 911 GT3'];  
		
		transaction.executeSql("INSERT INTO page_settings(id, fname, bgcolor, font, favcar) VALUES (?, ?, ?, ?, ?)", [data[0], data[1], data[2], data[3], data[4]]);
	    }
	);	
}

/***
**** UPDATE TABLE ** 
***/
function updateSetting(){
	DEMODB.transaction(
	    function (transaction) {
	    	if($('#fname').val() != '') {
	    		var fname = $('#fname').val();
	    	} else {
	    		var fname = 'none';
	    	}
			
			var bg    = $('#bg_color').val();
			var font  = $('#font_selection').val();
			var car   = $('#fav_car').val();
			
	    	
	    	transaction.executeSql("UPDATE page_settings SET fname=?, bgcolor=?, font=?, favcar=? WHERE id = 1", [fname, bg, font, car]);
	    }
	);	
		selectAll();
}
function selectAll(){ 
	DEMODB.transaction(
	    function (transaction) {

	        transaction.executeSql("SELECT * FROM page_settings;", [], dataSelectHandler, errorHandler);
	        
	    }
	);	
}

function dataSelectHandler(transaction, results){

	// Handle the results
    for (var i=0; i<results.rows.length; i++) {
        
    	var row = results.rows.item(i);
    	
        var newFeature = new Object();
    	
    	newFeature.fname   = row['fname'];
        newFeature.bgcolor = row['bgcolor'];
        newFeature.font    = row['font'];
        newFeature.favcar  = row['favcar'];
        
        $('body').css('background-color',newFeature.bgcolor);
        $('body').css('font-family',newFeature.font);
        $('#content').html('<h4 id="your_car">Your Favorite Car is a '+ newFeature.favcar +'</h4>');
        
        if(newFeature.fname != 'none') {
       		$('#greeting').html('Howdy-ho, '+ newFeature.fname+'!');
       		$('#fname').val(newFeature.fname);
        } 
        
       $('select#font_selection').find('option[value='+newFeature.font+']').attr('selected','selected');
       $('select#bg_color').find('option[value='+newFeature.bgcolor+']').attr('selected','selected');  
       $('select#fav_car').find('option[value='+newFeature.favcar+']').attr('selected','selected');

       
    }

}


/***
**** Save 'default' data into DB table **
***/

function saveAll(){
		prePopulate(1);
}


function errorHandler(transaction, error){
 	if (error.code==1){
 		// DB Table already exists
 	} else {
    	// Error is a human-readable string.
	    console.log('Oops.  Error was '+error.message+' (Code '+error.code+')');
 	}
    return false;
}


function nullDataHandler(){
	console.log("SQL Query Succeeded");
}

/***
**** SELECT DATA **
***/
function selectAll(){ 
	DEMODB.transaction(
	    function (transaction) {
	        transaction.executeSql("SELECT * FROM page_settings;", [], dataSelectHandler, errorHandler);
	    }
	);	
}

/***
**** DELETE DB TABLE ** 
***/
function dropTables(){
	DEMODB.transaction(
	    function (transaction) {
	    	transaction.executeSql("DROP TABLE page_settings;", [], nullDataHandler, errorHandler);
	    }
	);
	console.log("Table 'page_settings' has been dropped.");
	location.reload();
}


##################################################################################### ## ## MOD Title: AUCTION MOD 1.3m ## MOD Author: FR (www.phpbb-auction.com) ## MOD Description: - ## MOD Version: 1.3m ## ## Installation Level: (Middle) ## Installation Time: till your done ## ## Requirements: A running phpBB 2.0.x (lastest version recommended) ## GD 1.8.x - 2.0 or higher (require for auto-thumbnail ## HTTP File Upload Enabled ## ## Tested with: __________ ## ## Files To Edit: viewonline.php ## viewtopic.php ## admin/index.php ## includes/usercp_viewprofile.php ## includes/page_header.php ## language/lang_english/lang_admin.php ## language/lang_english/lang_main.php ## templates/subSilver/subSilver.cfg ## templates/subSilver/overall_header.tpl ## templates/subSilver/viewtopic_body.tpl ## templates/subSilver/profile_view_body.tpl ## ## Included Files: to much to mention ## ##################################################################################### ## ## Before Adding This MOD To Your Forum, You Should Back Up All Files ## Related To This MOD ## ##################################################################################### ## ## For Security Purposes, you should check www.phpbb-auction.com for news and patches ## ##################################################################################### ## ## Author Notes: ## ## ##################################################################################### ## ## This hack is released under the GPL License. ## This hack can be freely used, but not distributed, without permission. ## Intellectual Property is retained by the author listed above. ## ##################################################################################### # # If you have the phpbb-auction 1.2m installed you should use the update.txt # document. # # #-----[ COPY ]------------------------------------------------------- # # Upload all files in directory "phpbb_root" with their structure to your # phpBB root directory # # Remember to upload all the language files and template files to all your # language packs and template directories # # If you use FTP please remember to use ASCII mode for text files (*.php, *.tpl) # and BINARY mode for image files (*.jpg, *.gif) # Fortunately good FTP clients today can auto-detect the mode for your files # #-----[ ACTION ]-------------------------------------- # Require for Unix-like host (you can use your FTP client to do this) # # CHMOD 777 auction/upload/ # CHMOD 777 auction/upload/cache/ # CHMOD 777 auction/upload/main/ # CHMOD 777 auction/upload/main/watermark/ # CHMOD 777 auction/upload/mini/ # CHMOD 777 auction/upload/tmp/ # CHMOD 777 auction/upload/wmk/ # CHMOD 777 auction/upload/watermark/ # CHMOD 777 auction/upload/wmk/main_watermark.png # CHMOD 777 auction/upload/wmk/big_watermark.png # #-----[ ACTION ]-------------------------------------- # # Run the install_db.php and delete (!!!) the file afterwards //////////////////////////////////////////////////////////////////////////////// 3 - Perform the following filechanges //////////////////////////////////////////////////////////////////////////////// # #-----[ OPEN ]------------------------------------------ # viewonline.php # #-----[ FIND ]------------------------------------------ # include($phpbb_root_path . 'includes/page_header.'.$phpEx); # #-----[ AFTER, ADD ]------------------------------------------ # include($phpbb_root_path . 'auction/auction_common.'.$phpEx); # #-----[ FIND ]------------------------------------------ # case PAGE_FAQ: $location = $lang['Viewing_FAQ']; $location_url = "faq.$phpEx"; break; # #-----[ AFTER, ADD ]------------------------------------------ # case AUCTION_ROOM: $location = $lang['Auction']; $location_url = "auction.$phpEx"; break; case AUCTION_OFFER: $location = $lang['Auction']; $location_url = "auction.$phpEx"; break; case AUCTION_RATING: $location = $lang['Auction']; $location_url = "auction.$phpEx"; break; case AUCTION_FAQ: $location = $lang['Auction']; $location_url = "auction.$phpEx"; break; case AUCTION_MYAUCTION: $location = $lang['Auction']; $location_url = "auction.$phpEx"; break; case AUCTION_OFFER_VIEW: $location = $lang['Auction']; $location_url = "auction.$phpEx"; break; case AUCTION_SITEMAP: $location = $lang['Auction']; $location_url = "auction.$phpEx"; break; case AUCTION_PIC_MANAGER: $location = $lang['Auction']; $location_url = "auction.$phpEx"; break; # #-----[ OPEN ]------------------------------------------ # admin/index.php # #-----[ FIND ]------------------------------------------ # require('./pagestart.' . $phpEx); # #-----[ AFTER, ADD ]------------------------------------------ # include($phpbb_root_path . 'auction/auction_common.'.$phpEx); # #-----[ FIND ]------------------------------------------ # # 2 times case PAGE_FAQ: $location = $lang['Viewing_FAQ']; $location_url = "index.$phpEx?pane=right"; break; # #-----[ AFTER, ADD ]------------------------------------------ # # 2 times case AUCTION_ROOM: $location = $lang['Auction']; $location_url = "auction.$phpEx?pane=right"; break; case AUCTION_OFFER: $location = $lang['Auction']; $location_url = "auction.$phpEx?pane=right"; break; case AUCTION_RATING: $location = $lang['Auction']; $location_url = "auction.$phpEx?pane=right"; break; case AUCTION_FAQ: $location = $lang['Auction']; $location_url = "auction.$phpEx?pane=right"; break; case AUCTION_MYAUCTION: $location = $lang['Auction']; $location_url = "auction.$phpEx?pane=right"; break; case AUCTION_OFFER_VIEW: $location = $lang['Auction']; $location_url = "auction.$phpEx?pane=right"; break; case AUCTION_SITEMAP: $location = $lang['Auction']; $location_url = "auction.$phpEx?pane=right"; break; case AUCTION_PIC_MANAGER: $location = $lang['Auction']; $location_url = "auction.$phpEx?pane=right"; break; # #-----[ OPEN ]------------------------------------------ # /language/lang_english/lang_admin.php # #-----[ FIND ]------------------------------------------ # $lang['Styles'] = 'Styles Admin'; # #-----[ AFTER, ADD ]------------------------------------------ # $lang['Auction'] = 'Auction'; $lang['a1_configuration'] = 'Configuration'; $lang['a2_roommangement'] = 'Manage Rooms'; $lang['a4_coupons'] = 'Manage Coupons'; $lang['a3_offer'] = 'Manage Offers'; $lang['a5_ipn_log'] = 'Manage IPN Log'; $lang['a6_picture_Configuration'] = 'Manage Images'; $lang['a7_permission'] = 'Manage Permissions'; $lang['a8_account'] = 'Manage Account'; # #-----[ OPEN ]------------------------------------------ # /templates/subSilver/subSilver.cfg # #-----[ FIND ]------------------------------------------ # $current_template_images = $current_template_path . "/images"; # #-----[ AFTER, ADD ]------------------------------------------ # $images['auction_locked']="$current_template_images/auction_locked.gif"; $images['auction_open']="$current_template_images/auction_open.gif"; $images['icon_auction_delete']="$current_template_images/auction_delete.gif"; $images['icon_auction_move']="$current_template_images/auction_move.gif"; $images['icon_auction_pic']="$current_template_images/auction_pic.gif"; $images['icon_auction_no_pic']="$current_template_images/auction_nopic.gif"; $images['icon_auction_down']="$current_template_images/auction_down.gif"; $images['icon_auction_up']="$current_template_images/auction_up.gif"; $images['icon_auction_feature']="$current_template_images/auction_feature.gif"; $images['icon_rating1']="$current_template_images/rating/1.gif"; $images['icon_rating2']="$current_template_images/rating/2.gif"; $images['icon_rating3']="$current_template_images/rating/3.gif"; $images['icon_rating4']="$current_template_images/rating/4.gif"; $images['icon_auction_watch']="$current_template_images/auction_add.gif"; $images['icon_auction_user_rating'] = "$current_template_images/{LANG}/icon_auction_user_rating.gif"; $images['newoffer'] = "$current_template_images/{LANG}/newoffer.gif"; $images['direct_sell'] = "$current_template_images/{LANG}/auction_buy_now.gif"; $images['vote_left'] = "$current_template_images/vote_lcap.gif"; $images['vote_right'] = "$current_template_images/vote_rcap.gif"; $images['auction_vote_right'] = "$current_template_images/auction_voting_barb.gif"; $images['auction_vote'] = "$current_template_images/auction_voting_bar.gif"; # #-----[ OPEN ]------------------------------------------ # /language/lang_english/lang_main.php # #-----[ FIND ]------------------------------------------ # $lang['datetime']['Dec'] = 'Dec'; # #-----[ AFTER, ADD ]------------------------------------------ # // Auction $lang['Auction'] = 'Auction'; # #-----[ OPEN ]------------------------------------------ # /templates/subSilver/overall_header.tpl # #-----[ FIND ]------------------------------------------ # <a href="{U_GROUP_CP}" class="mainmenu"><img src="templates/subSilver/images/icon_mini_groups.gif" width="12" height="13" border="0" alt="{L_USERGROUPS}" hspace="3" />{L_USERGROUPS}</a> # #-----[ AFTER, ADD ]------------------------------------------ #   <a href="{U_AUCTION}" class="mainmenu"><img src="templates/subSilver/images/icon_mini_auction.gif" width="12" height="13" border="0" alt="{L_AUCTION}" hspace="3" />{L_AUCTION}</a> # #-----[ OPEN ]------------------------------------------ # includes/page_header.php # #-----[ FIND ]------------------------------------------ # 'L_FAQ' => $lang['FAQ'], # #-----[ AFTER, ADD ]------------------------------------------ # 'L_AUCTION' => $lang['Auction'], # #-----[ FIND ]------------------------------------------ # 'U_FAQ' => append_sid('faq.'.$phpEx), # #-----[ AFTER, ADD ]------------------------------------------ # 'U_AUCTION' => append_sid('auction.'.$phpEx), # #-----[ OPEN ]------------------------------------------ # viewtopic.php # #-----[ FIND ]------------------------------------------ # include($phpbb_root_path . 'includes/bbcode.'.$phpEx); # #-----[ AFTER, ADD ]------------------------------------------ # // Start Include language file $language = $board_config['default_lang']; if( !file_exists($phpbb_root_path . 'language/lang_' . $language . '/lang_auction.'.$phpEx) ) { $language = 'english'; } include($phpbb_root_path . 'language/lang_' . $language . '/lang_auction.' . $phpEx); // end include language file # #-----[ FIND ]------------------------------------------ # 'L_MINI_POST_ALT' => $mini_post_alt, # #-----[ AFTER, ADD ]------------------------------------------ # 'AUCTION_USER_RATING' => "<a href=" . append_sid("auction_rating.php?mode=view&" . POST_USERS_URL . "=" .$poster_id ) . "><img src=" . $images['icon_auction_user_rating'] . " alt='Feedback Rating' border='0' /></a>", 'L_VIEW_AUCTION_USER_RATING' => $lang['auction_user_rating'], # #-----[ OPEN ]------------------------------------------ # includes/usercp_viewprofile.php # #-----[ FIND ]------------------------------------------ # if ( !defined('IN_PHPBB') ) { die("Hacking attempt"); exit; } # #-----[ AFTER, ADD ]------------------------------------------ # // Start Include language file $language = $board_config['default_lang']; if( !file_exists($phpbb_root_path . 'language/lang_' . $language . '/lang_auction.'.$phpEx) ) { $language = 'english'; } include($phpbb_root_path . 'language/lang_' . $language . '/lang_auction.' . $phpEx); // end include language file # #-----[ FIND ]------------------------------------------ # 'AVATAR_IMG' => $avatar_img, # #-----[ AFTER, ADD ]------------------------------------------ # 'AUCTION_USER_RATING' => "<a href=\"" . append_sid("auction_rating.php?mode=view&" . POST_USERS_URL . "=" . $profiledata['user_id'] ) . "\"><img src=\"" . $images['icon_auction_user_rating'] . "\" alt=\"" . $lang['auction_user_rating'] . "\" title=\"" . $lang['auction_user_rating'] . "\" border=\"0\" /></a>", 'L_VIEW_AUCTION_USER_RATING' => $lang['auction_user_rating'], # #-----[ OPEN ]------------------------------------------ # /templates/subSilver/viewtopic_body.tpl # #-----[ FIND ]------------------------------------------ # {postrow.MSN_IMG} # #-----[ AFTER,ADD ]------------------------------------------ # // Goes in same line before {postrow.MSN_IMG} {postrow.AUCTION_USER_RATING} # #-----[ OPEN ]------------------------------------------ # /templates/subSilver/profile_view_body.tpl # #-----[ FIND ]------------------------------------------ # <tr> <td valign="middle" nowrap="nowrap" align="right"><span class="gen">{L_AIM}:</span></td> <td class="row1" valign="middle"><span class="gen">{AIM_IMG}</span></td> </tr> # #-----[ AFTER, ADD ]------------------------------------------ # <tr> <td valign="middle" nowrap="nowrap" align="right"><span class="gen">{L_VIEW_AUCTION_USER_RATING}:</span></td> <td class="row1" valign="middle"><span class="gen">{AUCTION_USER_RATING}</span></td> </tr> # #-----[ SAVE/CLOSE ALL FILES ]------------------------------------------ # ##################################################################################### ## Further Information ## ## Thats it! You are through. If you have any questions dont hesitate to use the ## Support Forums on www.phpbb-auction.com. If you want to use the payment methods ## you should read the documentation for it on the projects website. ## Greetings and have fun with phpbb-Auction ## FR ## EoM #####################################################################################
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值