使用cordova在sqlite数据库中插入的值

时间:2014-09-08 07:47:07

标签: android sqlite jquery-mobile cordova

我创建了一个表单,用于将数据从文本框插入到数据库中,当我在浏览器中运行它时,我可以看到表已创建并插入了值。

我尝试使用cordova实现相同的功能,并且创建了表格,并且没有插入值..

这是我的编码 ..

document.addEventListener("deviceready",  function()
{
var db=window.sqlitePlugin.openDatabase({name : "mydb"});
var createStatement = "CREATE TABLE IF NOT EXISTS login(id INTEGER PRIMARY KEY AUTOINCREMENT,username      TEXT,password TEXT,firstname TEXT, lastname TEXT,hobby  TEXT,email TEXT)";
var insertStatement = " INSERT INTO login(username,password,firstname,lastname,hobby,email) VALUES (?,?,?,?,?,? ) ";
function initDatabase()  // Function Call When Page is ready.

{

try {

    if (!window.openDatabase)  // Check browser is supported SQLite or not.

    {

       // alert('Databases are not supported in this browser.');

    }

    else {

        createTable();  // If supported then call Function for create table in SQLite

    }

 }

 catch (e) {

    if (e == 2) {

        // Version number mismatch. 

        console.log("Invalid database version.");

    } else {

        console.log("Unknown error " + e + ".");

    }

    return;

   }

   }


   function createTable() // Function Call When Page is ready.

   {


   var res=db.transaction(function (tx) { tx.executeSql(createStatement, [], onError); });

  alert("Successfully created the table");

   }
  function onError(tx, error) // Function for Hendeling Error...

   {

 // alert(error.message);

  }
  });
  document.addEventListener("deviceready",  function()
  {
  var db=window.sqlitePlugin.openDatabase({name : "mydb"});         

  function insertRecord()
  {
    var usernameold = $('input:text[id=username]').val();

    var passwordold = $('input:password[id=pass]').val();

     var firstnameold = $('input:text[id=firstname]').val();

    var lastnameold = $('input:text[id=lastname]').val();

    var hobbyold = $('input:text[id=hobby]').val();

    var emailold = $('input:text[id=email]').val();

    db.transaction(function (tx) { tx.executeSql(insertStatement,     [usernameold,passwordold,firstnameold, lastnameold,hobbyold,emailold]/*,loadAndReset, onError*/) });

    alert("Successfully created the table");
    }
   });

   $(document).ready(function()
   {
    initDatabase();
   $("#submit").click(insertRecord); 
   });

尝试从 fileexprorer-> data-> data-> projectpackage-> databases-> mydb.db

保存并导入数据库

然后 firefox-> sqlitemanager-> connectdb

我可以看到表格已经创建,而且值没有插入 Plz帮助...

2 个答案:

答案 0 :(得分:1)

可以插入值:

    db.transaction(function (tx) 
  { 
    tx.executeSql('INSERT INTO login (username,pass,firstname,lastname,hobby,email)VALUES("'+un+'","'+ps+'","'+fs+'","'+ls+'","'+hb+'","'+ed+'")');

  });
  });
  }

哪里

   var un= $("#username").val();

   var ps= $("#pass").val();

   var fs = $('input:text[id=firstname]').val();

   var ls = $('input:text[id=lastname]').val();

   var hb = $('input:text[id=hobby]').val();

   var ed = $('input:text[id=email]').val();

答案 1 :(得分:0)

http://docs.phonegap.com/en/1.2.0/phonegap_storage_storage.md.html检查数据库存储查询的上述链接。    尝试使用以下代码。希望这会对你有所帮助。

     <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>

    <script type="text/javascript" charset="utf-8">     
        document.addEventListener("deviceready", onDeviceReady, false);    
        var nameval,pwdval,fnameval,lnameval,hobbyval,emailval;

function onDeviceReady() {          
    var db = window.openDatabase("Logindetails_DB", "1.0", "Logindetails_DB", 100000);      
    db.transaction(populateDB, errorCB, successCB);
}

function validationCheck(){
     nameval=document.getElementById('u_name').value;
     pwdval=document.getElementById('u_pwd').value;
     fnameval=document.getElementById('u_firstname').value;
     lnameval=document.getElementById('u_lastname').value;
     hobbyval=document.getElementById('u_hobby').value;
     emailval=document.getElementById('u_email').value;
            if(document.getElementById('u_name').value==""){
                    alert('Enter Your Name');                       
            }
             if(document.getElementById('u_pwd').value==""){
                alert('Enter Your Password');                   
            }   
            if(document.getElementById('u_firstname').value==""){
                    alert('Enter Your FirstName');                      
            }
            if(document.getElementById('u_lastname').value==""){
                    alert('Enter Your LastName');                       
            }
            if(document.getElementById('u_hobby').value==""){
                    alert('Enter Your HobbyName');                      
            }
            if(document.getElementById('u_email').value==""){
                    alert('Enter Your Email');                      
            }           
             if(nameval!='' && pwdval!='' && fnameval!='' && lnameval!='' && hobbyval!='' && emailval!=''){ 
             alert('Name'+nameval+'Pwd'+pwdval);                    
                    Insertvalue();                      
                 }

}

function Insertvalue(){
        var db = window.openDatabase("Logindetails_DB", "1.0", "Logindetails_DB", 100000);
         db.transaction(getregistdata, transaction_error);                        
    }   
        function getregistdata(tx){
            tx.executeSql('INSERT INTO login (username, password, firstname,lastname,hobby,email) VALUES ("'+nameval+'", "'+pwdval+'","'+fnameval+'","'+lnameval+'","'+hobbyval+'","'+emailval+'")');
                        alert('Record Inserted Successfully');
                }

        function transaction_error(tx, error) {
         alert("Database Error: " + error);
        }           


// Populate the database

   function populateDB(tx) {    
            tx.executeSql('CREATE TABLE IF NOT EXISTS login(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT NULL, firstname TEXT NOT NULL,lastname TEXT NOT NULL,hobby TEXT NOT NULL,email TEXT NOT NULL)');              

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

// Transaction success callback
//
function successCB() {
    alert("success!");

} 
</script>
 </head>
<body>

   <h1>Hello PhoneGap</h1>
    <form name="form1" id="form1" method="post">
        User Name: <br><input type="text" name="u_name" id="u_name"><br><br>
        Password:<br><input type="text" name="u_pwd" id="u_pwd"><br><br>
        First Name<br> <input type="text" name="u_firstname" id="u_firstname"><br><br>
        Last Name<br> <input type="text" name="u_lastname" id="u_lastname"><br><br>
        Hobby<br> <input type="text" name="u_hobby" id="u_hobby"><br><br>
        Email<br> <input type="text" name="u_email" id="u_email"><br><br>
   <div style="text-align:center;">
      <input type="button" name="submitbtn" id="submitbtn" value="Submit" onclick="validationCheck()">
   </div>
  </form>

  </body>
   </html>