如何在PhoneGap中创建数据库?

时间:2015-01-30 12:22:04

标签: javascript android cordova database-connection

我是android PhoneGap的新手。

<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<script type="text/javascript" charset="utf-8">

    document.addEventListener("deviceready", onDeviceReady, false);

    function onDeviceReady() {
        var db = window.openDatabase("raddyx", "1.0", "Cordova Demo", 200000);
        db.transaction(populateDB, errorCB, successCB);
    }
    function populateDB(tx) {
        tx.executeSql('DROP TABLE IF EXISTS DEMO');
        tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
        tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
    }

    function errorCB(tx, err) {
        alert("Error processing SQL: "+err);
    }

    function successCB() {
        alert("success!");
    }

</script>

我正在使用上面的示例代码。我的数据库名称raddyx。我无法创建数据库。你能告诉我如何在PhoneGap中创建raddyx数据库吗?

编辑 - 当我在我的手机中运行时,它显示Unfortunately, APP_NAME_HERE has stopped.如果我删除了我的连接代码,它可以正常工作。

1 个答案:

答案 0 :(得分:0)

您可以使用以下函数创建数据库:

function queryDB() {
        var db = window.openDatabase("Database", "1.0", "Cordova login", 300000);

        db.transaction(inputDb, errorCB);
    }

之后,调用函数inputDb,如下所示:

function inputeDb(db2) {    
                db2.executeSql('DROP TABLE IF EXISTS login');
                db2.executeSql('CREATE TABLE IF NOT EXISTS login (id_Login INTEGER PRIMARY KEY AUTOINCREMENT, UserName VARCHAR(150) NULL, UserPassword VARCHAR(100) NULL, UserHash VARCHAR(50) NULL)');
                db2.executeSql('INSERT INTO login (UserName, UserPassword) VALUES ("'+uname1+'", "'+upass1+'")');

                db2.executeSql('DROP TABLE IF EXISTS MDataT');
                db2.executeSql('CREATE TABLE IF NOT EXISTS MDataT (id_MData INTEGER PRIMARY KEY, MData INTEGER)');
                db2.executeSql('INSERT INTO MDataT (id_MData, MData) VALUES ("1", "'+MData+'")');

                //alert("Username and Password - Set in DB");
                location.href="serverLogin.html";
            }