本文介绍了检查DB是否存在,并在SQLLite IOS中删除DB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用phonegap来创建和ios应用程序。



在熟悉sql javascript交互时,我似乎创建了10个版本的同一个命名数据库文件。



我目前正在使用以下创建代码(来自phonegap wiki)

  var mydb = false; 
//初始化数据库
initDB = function(){
try {
if(!window.openDatabase){
alert('not supported');
} else {
var shortName ='Phonegap';
var version ='1.0';
var displayName ='PhoneGap Test Database';
var maxSize = 65536; //以字节为单位
mydb = openDatabase(shortName,version,displayName,maxSize);
}
} catch(e){
//错误处理代码在这里。
if(e == INVALID_STATE_ERR){
//版本号不匹配。
alert(数据库版本无效。
} else {
alert(Unknown error+ e +。
}
return;
}
}
// db错误处理程序 - 防止事务的其余部分失败
errorHandler = function(transaction,error){
//返回true回滚事务
return true;
}
//空数据库数据处理程序
nullDataHandler = function(transaction,results){}

我的问题是,我不确定如何检查数据库是否存在之前创建它或如何创建它只有一个设备一次?



其次我如何删除所有这些已创建的数据库。

  transaction.executeSql('DROP DATABASE phonegap;'); 

似乎没有掉落任何东西。



感谢

解决方案

请尝试以下代码。它不是创建多个数据库文件,只需通过访问位置交叉验证 -

 / Users / {username} / Library / Application Support / iPhone Simulator / 4.3 / Applications / {3D5CD3CC-C35B-41B3-BF99-F1E4B048FFFF } / Library / WebKit / Databases / file__0 



这是sqlite3示例,其中包含对表的创建,插入,删除和删除查询。

 <!DOCTYPE html> 
< html>
< body style =font:75%Lucida Grande,Trebuchet MS>
< div id =content>< / div>
< p id =logstyle =color:gray>< / p>
< script>
document.getElementById('content')。innerHTML =
' < h4>简单待办事项清单< / h4>'+
'< ul id =results>< / ul>< div> Handle Database in Phonegap< / div>'+
'< button onclick =newRecord()> new record< / button>'+
'< button onclick =createTable()> create table< / button>'+
' < button onclick =dropTable()> drop table< / button>';
var db;
var log = document.getElementById('log');
db = openDatabase(DBTest,1.0,HTML5 Database API example,200000);
showRecords();
document.getElementById('results')。addEventListener('click',function(e){e.preventDefault();},false);
function onError(tx,error){
log.innerHTML + ='< p>'+ error.message +'< / p>';
}
//选择所有记录并显示它们
function showRecords(){
document.getElementById('results')。innerHTML ='';
db.transaction(function(tx){
tx.executeSql(SELECT * FROM Table1Test,[],function(tx,result){
for(var i = 0,item = null; i< result.rows.length; i ++){
item = result.rows.item(i);
document.getElementById('results')。innerHTML + =
' < li>< span contenteditable =trueonkeyup =updateRecord('+ item ['id'] +',this)>'+
item ['id'] + 'text'] +'< / span>< a href =#onclick =deleteRecord('+ item ['id'] +')> x< / a>< / li> b $ b}
});
});
}
function createTable(){
db.transaction(function(tx){
tx.executeSql(CREATE TABLE Table1Test(id REAL UNIQUE,text TEXT) ],
function(tx){log.innerHTML ='Table1Test created'},
onError);
});
}
//用随机值添加记录
function newRecord(){
var num = Math.round(Math.random()* 10000); //随机数据
db.transaction(function(tx){
tx.executeSql(INSERT INTO Table1Test(id,text)VALUES(?,?),[num,'Record: ,
function(tx,result){
log.innerHTML ='record added';
showRecords();
},
onError);
});
}
function updateRecord(id,textEl){
db.transaction(function(tx){
tx.executeSql(UPDATE Table1Test SET text =?WHERE id =? ,[textEl.innerHTML,id],null,onError);
});
}
function deleteRecord(id){
db.transaction(function(tx){
tx.executeSql(DELETE FROM Table1Test WHERE id =?,[id]
function(tx,result){showRecords()},
onError);
});
}
//从db
中删除表函数dropTable(){
db.transaction(function(tx){
tx.executeSql(DROP TABLE Table1Test ,[],
function(tx){showRecords()},
onError);
});
}
< / script>
< / body>
< / html>

关于删除数据库...
对于像SQLite这样的嵌入式数据库引擎似乎没有意义。
要创建新数据库,只需执行sqlite_open()。
要删除数据库,只需删除该文件即可。



感谢,

Mayur


I'm currently using phonegap to create and ios app.

While getting familiar to the sql javascript interactions I seem to have created 10 versions of the same named database file.

I'm currently using the following creation code (from the phonegap wiki)

var mydb=false;
// initialise the database
initDB = function() {
  try {
    if (!window.openDatabase) {
      alert('not supported');
    } else {
      var shortName = 'phonegap';
      var version = '1.0';
      var displayName = 'PhoneGap Test Database';
      var maxSize = 65536; // in bytes
      mydb = openDatabase(shortName, version, displayName, maxSize);
     }
  } catch(e) {
    // Error handling code goes here.
    if (e == INVALID_STATE_ERR) {
      // Version number mismatch.
      alert("Invalid database version.");
    } else {
      alert("Unknown error "+e+".");
    }
    return;
  }
}
// db error handler - prevents the rest of the transaction going ahead on failure
    errorHandler = function (transaction, error) {
      // returns true to rollback the transaction
    return true;
          }
// null db data handler
    nullDataHandler = function (transaction, results) { }

my problem is that I'm unsure how to check if the database exists before creating it or how to create it only once per device?

and secondly how can i drop all these databases that have been created.

transaction.executeSql('DROP DATABASE phonegap;');

does not seem to drop anything.

Thanks

解决方案

Please try following code. it is not creating multiple database files, just cross verify by visiting location -

/Users/{username}/Library/Application Support/iPhone Simulator/4.3/Applications/{3D5CD3CC-C35B-41B3-BF99-F1E4B048FFFF}/Library/WebKit/Databases/file__0


This is sqlite3 example which cover create, insert, delete and drop queries on Table.

<!DOCTYPE html>
<html>
  <body style="font: 75% Lucida Grande, Trebuchet MS">
    <div id="content"></div>
    <p id="log" style="color: gray"></p>
    <script>
      document.getElementById('content').innerHTML =
        '<h4>Simple to do list</h4>'+
        '<ul id="results"></ul><div>Handle Database in Phonegap</div>'+
        '<button onclick="newRecord()">new record</button>'+
        '<button onclick="createTable()">create table</button>' +
        '<button onclick="dropTable()">drop table</button>';
      var db;
      var log = document.getElementById('log');
      db = openDatabase("DBTest", "1.0", "HTML5 Database API example", 200000);
      showRecords();
      document.getElementById('results').addEventListener('click', function(e) { e.preventDefault(); }, false);
      function onError(tx, error) {
        log.innerHTML += '<p>' + error.message + '</p>';
      }
      // select all records and display them
      function showRecords() {
        document.getElementById('results').innerHTML = '';
        db.transaction(function(tx) {
          tx.executeSql("SELECT * FROM Table1Test", [], function(tx, result) {
            for (var i = 0, item = null; i < result.rows.length; i++) {
              item = result.rows.item(i);
              document.getElementById('results').innerHTML +=
                  '<li><span contenteditable="true" onkeyup="updateRecord('+item['id']+', this)">'+
                  item['id']+' '+item['text'] + '</span> <a href="#" onclick="deleteRecord('+item['id']+')">x</a></li>';
            }
          });
        });
      }
      function createTable() {
        db.transaction(function(tx) {
          tx.executeSql("CREATE TABLE Table1Test (id REAL UNIQUE, text TEXT)", [],
              function(tx) { log.innerHTML = 'Table1Test created' },
              onError);
        });
      }
      // add record with random values
      function newRecord() {
        var num = Math.round(Math.random() * 10000); // random data
        db.transaction(function(tx) {
          tx.executeSql("INSERT INTO Table1Test (id, text) VALUES (?, ?)", [num, 'Record:'],
              function(tx, result) {
                log.innerHTML = 'record added';
                showRecords();
              },
              onError);
        });
      }
      function updateRecord(id, textEl) {
        db.transaction(function(tx) {
          tx.executeSql("UPDATE Table1Test SET text = ? WHERE id = ?", [textEl.innerHTML, id], null, onError);
        });
      }
      function deleteRecord(id) {
        db.transaction(function(tx) {
          tx.executeSql("DELETE FROM Table1Test WHERE id=?", [id],
              function(tx, result) { showRecords() },
              onError);
        });
      }
      // delete table from db
      function dropTable() {
        db.transaction(function(tx) {
          tx.executeSql("DROP TABLE Table1Test", [],
              function(tx) { showRecords() },
              onError);
        });
      }
     </script>
  </body>
</html>

And about Droping Database...Does not seem meaningful for an embedded database engine like SQLite.
To create a new database, just do sqlite_open().
To drop a database, simply delete the file.

thanks,
Mayur

这篇关于检查DB是否存在,并在SQLLite IOS中删除DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 09:10