App下載

在HTML5中我們應該如何連接數(shù)據(jù)庫?

猿友 2021-06-05 09:39:51 瀏覽數(shù) (6153)
反饋

在我們學習編程語言的時候肯定會比較多的聽到數(shù)據(jù)庫連接,那么為什么要連接數(shù)據(jù)庫呢?因為他可以做到數(shù)據(jù)的一個共享、減少一個數(shù)據(jù)的冗余度、實現(xiàn)數(shù)據(jù)的一個集中的控制、確保數(shù)據(jù)的安全可靠性和數(shù)據(jù)的一致性可維護性。那么在 HTML5 中我們應該如何連接數(shù)據(jù)庫呢?在數(shù)據(jù)庫的連接中我們需要使用 openDatabase、transaction和 executeSql 這三個方法,接下來我們就來說說怎么連接吧!


步驟一:


打開開發(fā)工具連接數(shù)據(jù)庫創(chuàng)建一個新的數(shù)據(jù)庫,代碼如下:

var dataBase = openDatabase("student", "1.0", "student", 1024 * 1024, function () { });
if (!dataBase) {
alert("數(shù)據(jù)庫創(chuàng)建失敗!");
} else {
alert("數(shù)據(jù)庫創(chuàng)建成功!");
}

步驟二:


完成一個數(shù)據(jù)庫之后在進行一個數(shù)據(jù)庫表格的創(chuàng)建,用來存取數(shù)據(jù)。代碼如下:

this.createTable = function() {

dataBase.transaction(function(tx) {

tx.executeSql(

"create table if not exists stu (id REAL UNIQUE, name TEXT)",

[],

function(tx, result) {

alert('創(chuàng)建stu表成功');

},

function(tx, error) {

alert('創(chuàng)建stu表失敗:' + error.message);

});

});

}


步驟三:


完成表格創(chuàng)建之后我們需要進行一個執(zhí)行數(shù)據(jù)庫的增刪改查的步驟,代碼如下:

this.insert = function() {
		dataBase.transaction(function(tx) {
			tx.executeSql(
				"insert into stu (id, name) values(?, ?)",
				[id, '小明'],
				function() {
					alert('添加數(shù)據(jù)成功');
				},
				function(tx, error) {
					alert('添加數(shù)據(jù)失敗: ' + error.message);
				});
		});


總結:

以上就是一個有關于在 HTML5 中我們應該如何連接數(shù)據(jù)庫的一個方法,當然如果你有更好的方法也可以分享給小編喔!想更深入的了解數(shù)據(jù)庫的話可以在HTML5 Web SQL進行學習和了解喔!也希望小編的分享對你有所幫助!



0 人點贊