Javascript 如何以编程方式删除 WebSQL 中的数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7183049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete a database in WebSQL programmatically?
提问by u283863
I am new to Web SQL databaseand I use it to save data in a local database in a web page.
我是Web SQL 数据库的新手,我使用它在网页的本地数据库中保存数据。
I can createa databaseby
我可以创建一个数据库,由
var db = openDatabase('database', '1.0', 'my database', 2 * 1024 * 1024);
and I can createa tableby doing this
我可以通过这样做创建一个表
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS mytable (blah,blah)');
});
I can deletethe tableby
我可以删除该表通过
db.transaction(function (tx) {
tx.executeSql('DROP TABLE mytable');
});
but is there a way to delete the database
programmatically?
但是有没有办法以database
编程方式删除?
采纳答案by serg
回答by i_a
Using PersistenceJS there is a persistence.reset API which will wipe the database clean. PersistenceJS Site
使用 PersistenceJS 有一个 persistence.reset API 可以清除数据库。 PersistenceJS 站点
For developing / testing purposes, you can view content and delete webSQL, IndexedDB, cookies, etc by searching for your domain name at this URL in Chrome:
出于开发/测试目的,您可以通过在 Chrome 中的以下 URL 搜索您的域名来查看内容并删除 webSQL、IndexedDB、cookie 等:
chrome://settings/cookies
There, you can delete all the storage for a domain or just certain local storage entities. Yes, the URL implies just 'cookies', but the interface at this URL includes all types of offline storage.
在那里,您可以删除域的所有存储或仅删除某些本地存储实体。是的,该 URL 仅表示“cookies”,但此 URL 上的界面包括所有类型的离线存储。
It would be great I think if the Chrome developer tools interface had the ability to right-click and delete a data storage entity in the Resources tab along with inspecting the content. But for now, all I know of is the settings/cookies URL.
我认为如果 Chrome 开发人员工具界面能够在资源选项卡中右键单击并删除数据存储实体以及检查内容,那就太好了。但就目前而言,我所知道的只是设置/cookies URL。
回答by hisa_py
I am developing a phonegap+jquery-mobile+KO app with offline storage using web sql via persistencejs, and jasmine js for BDD.
我正在开发一个带离线存储的 phonegap+jquery-mobile+KO 应用程序,通过persistencejs 使用 web sql 和用于 BDD 的 jasmine js。
I'm working on some sort of "database cleaner" to be executed after each spec. When I was searching on how to drop a web sql database I read the reply https://stackoverflow.com/a/10929725/667598(in this thread/question), and went to see what's in that directory (Mac OS X).
我正在研究在每个规范之后执行的某种“数据库清理器”。当我搜索如何删除 web sql 数据库时,我阅读了回复https://stackoverflow.com/a/10929725/667598(在此线程/问题中),然后查看该目录中的内容(Mac OS X) .
cd ~/Library/Application\ Support/Google/Chrome/Default/databases
Inside you will see a Databases.db SQLite3 database, and directories for each origin. These directories are named with the pattern protocol_host_somenumber (I don't know what that number is). So for example, in my case, since my apps are just files I open in Google Chrome with the file:/// … protocol, I can see a file__0 directory. And for twitter and I can also see a http_twitter.com_0 and a https_twitter.com_0.
在里面你会看到一个 Databases.db SQLite3 数据库,以及每个来源的目录。这些目录以 protocol_host_somenumber 模式命名(我不知道那个数字是什么)。例如,就我而言,由于我的应用程序只是我在 Google Chrome 中使用 file:/// ... 协议打开的文件,因此我可以看到 file__0 目录。对于 twitter,我还可以看到一个 http_twitter.com_0 和一个 https_twitter.com_0。
Inside this directories all file names are just numbers. For example inside file__0 I found a file named 8 and another named 9. In my case, these files are websql database. I don't know if there also Indexed DB databases in chrome's Default/databases
dir.
在这个目录中,所有文件名都只是数字。例如在 file__0 中,我发现了一个名为 8 的文件和另一个名为 9 的文件。就我而言,这些文件是 websql 数据库。我不知道 chrome 的Default/databases
目录中是否也有索引数据库数据库。
With this names it is a little hard to guess what database is what. You can open the database and you'll have to infer the app or site via its tables and data.
有了这个名字,有点难以猜测数据库是什么。您可以打开数据库,然后必须通过其表和数据来推断应用程序或站点。
Luckily, the Databases.db I mentioned before is a mapping between those files named with numbers and the databases.
幸运的是,我之前提到的 Databases.db 是那些以数字命名的文件和数据库之间的映射。
You can open the Databases.db and any other web sql file with the sqlite3 command
您可以使用 sqlite3 命令打开 Databases.db 和任何其他 web sql 文件
sqlite3 Databases.db
Obviously, once inside the sqlite3 shell, is handy to have some SQL knowledge. Anyway, it is also always handy some help, which is available via the command
显然,一旦进入 sqlite3 shell,掌握一些 SQL 知识就很方便了。无论如何,它也总是很方便的一些帮助,可以通过命令获得
.help
With the command .tables
you can list tables in the database. Inside this Databases.db we can find the tables Databases and meta. The important one is Databases, so with a
使用该命令,.tables
您可以列出数据库中的表。在这个 Databases.db 中,我们可以找到表 Databases 和 meta。重要的是数据库,所以用
select * from Databases;
we can see the mapping between the databases and their files. For example
我们可以看到数据库和它们的文件之间的映射。例如
7|http_jquerymobile.com_0|testdb|html5 test db|200000
8|file__0|elfaro_dev|Base de datos de ElFaro para desarrollo|734003200
7|http_jquerymobile.com_0|testdb|html5 测试数据库|200000
8|file__0|elfaro_dev|Base de datos de ElFaro para desarrollo|734003200
The first column is the id of the table which is the number used for db file names, the second is the origin (the directory) the other columns are the db name, the db description and the estimated size used when creating the db from the Javascript API.
第一列是表的 id,它是用于 db 文件名的编号,第二列是来源(目录),其他列是 db 名称、db 描述和从数据库创建 db 时使用的估计大小Javascript API。
So to actually delete a database what I did was to delete it from this table, for example:
所以要真正删除一个数据库,我所做的是从这个表中删除它,例如:
delete from Databases where id = 8
And then delete the actual file from the filesystem (outside sqlite3 shell)
然后从文件系统中删除实际文件(在 sqlite3 shell 之外)
rm file__0/8
And that's it.
就是这样。
PS: I know this is a too long answer for a simple subject but I just needed to flush this from my system and back it up somewhere like SO or a blog.
PS:我知道这对于一个简单的主题来说是一个太长的答案,但我只需要从我的系统中刷新它并将其备份到 SO 或博客之类的地方。
回答by Endless
The developer options
开发者选项
There is no way to enumerate or delete the databases programmatically (yet).
Chrome developers can navigate to chrome://settings/cookies
search and delete any database
Opera developers can navigate to opera://settings/cookies
目前还没有办法以编程方式枚举或删除数据库。
Chrome 开发人员可以导航chrome://settings/cookies
搜索和删除 Opera 开发人员可以导航到的任何数据库opera://settings/cookies
The only way to truly delete a database (and everything else)
真正删除数据库(以及其他所有内容)的唯一方法
A new Specsays this might be possible in the featurewith both response header and javascript. The disadvantagesis that you can't control what is being deleted, So you would need to create a backup first of everything else unless you want to clear everything
一个新的规范说这在具有响应头和 javascript的特性中是可能的。的缺点是你无法控制被删除,所以,你会需要首先一切的创建备份,除非你想清楚一切
2.1.3. The storage parameter
The storage parameter indicates that the server wishes to remove locally stored data associated with the origin of a particular response's url. This includes storage mechansims such as (localStorage, sessionStorage, [INDEXEDDB], [WEBDATABASE], etc), as well as tangentially related mechainsm such as service worker registrations.
2.1.3. 存储参数
storage 参数表示服务器希望删除与特定响应的 url 的来源相关联的本地存储数据。这包括存储机制,例如(localStorage、sessionStorage、[INDEXEDDB]、[WEBDATABASE] 等),以及切线相关的机制,例如服务工作者注册。
Js:
JS:
navigator.storage.clear({
types: [ "storage" ],
includeSubdomains: true // false by default
});
Response header:
响应头:
res.header("Clear-Site-Data", "storage; includeSubdomains");
But this is not avalible to any browser yet...
但这还不适用于任何浏览器......
Best solution for clients (not the developers)
客户(而非开发人员)的最佳解决方案
/* This will fetch all tables from sqlite_master
* except some few we can't delete.
* It will then drop (delete) all tables.
* as a final touch, it is going to change the database
* version to "", which is the same thing you would get if
* you would check if it the database were just created
*
* @param name [string] - the database to delete
* @param cb [function] - the callback when it's done
*/
function dropDatabase(name, cb){
// empty string means: I do not care what version, desc, size the db is
var db = openDatabase(name, "", "", "");
function error(tx, err){
console.log(err);
}
db.transaction(ts => {
// query all tabels from sqlite_master that we have created and can modify
var query = "SELECT * FROM sqlite_master WHERE name NOT LIKE 'sqlite\_%' escape '\' AND name NOT LIKE '\_%' escape '\'";
var args = [];
var success = (tx, result) => {
var rows, i, n, name;
rows = result.rows;
n = i = rows.length;
// invokes cb once it's called n times
function after(){
if (--n < 0) {
// Change the database version back to empty string
// (same as when we compear new database creations)
db.changeVersion(db.version, "", function(){}, error, cb);
}
}
while(i--){
// drop all tabels and calls after() each time
name = JSON.stringify(rows.item(i).name);
tx.executeSql('DROP TABLE ' + name, [], after, error);
}
// call it just 1 more extra time incase we didn't get any tabels
after();
};
ts.executeSql(query, args, success, error);
});
}
Usage
用法
dropDatabase("database", function(){
console.log("done")
});
回答by Wytze
The localdatabase files are stored in your Windows user settings under Application Data > Google > Chrome > User Data > Default > databases.
本地数据库文件存储在您的 Windows 用户设置中,位于应用程序数据 > Google > Chrome > 用户数据 > 默认 > 数据库下。
So manually deleting them is theoretically possible. This is only useful while testing / developing on your own computer, since when another user opens your app/site, it is unlikely to have file system access.
所以理论上可以手动删除它们。这仅在您自己的计算机上测试/开发时有用,因为当另一个用户打开您的应用程序/站点时,它不太可能具有文件系统访问权限。
However, even though you can find the files and delete them, the data sticks around. I've tried it with Chrome both open and closed and all chrome processes ended, and yet the browser inspector keeps showing me my old database with all the unwanted fields and data in it.
但是,即使您可以找到文件并删除它们,数据仍然存在。我已经在 Chrome 打开和关闭的情况下尝试过它,并且所有 chrome 进程都结束了,但浏览器检查器一直向我显示我的旧数据库,其中包含所有不需要的字段和数据。
回答by Kyaw Tun
In my libraryimplementation, I just delete all tables. Which, indeed, delete the database. List of tables are select * from sqlite_master
.
在我的库实现中,我只是删除了所有表。其中,确实删除了数据库。表列表是select * from sqlite_master
.
回答by Boris Smus
This is answered in HTML5 database storage (SQL lite) - few questions.
这在HTML5 数据库存储 (SQL lite) - 几个问题中得到了回答。
To summarize:
总结一下:
- Currently no way to drop a WebSQL database.
- Probably use Indexed DB or localStorage instead.
- 目前无法删除 WebSQL 数据库。
- 可能使用索引数据库或 localStorage 代替。
回答by JimTheDev
Please note that if you use multiple
请注意,如果您使用多个
tx.executeSql('DROP TABLE mytable');
statements in the same transaction callback then make sure that they all exist or consider using DROP TABLE IF EXISTS syntax instead. If even one table doesn't exist when you try to drop it will result in the entire transaction failing. This failure results in a rollback of the transaction and means that the data will stay in your database even when you thought that it should have been deleted. There is no error reported unless you're specifically listening for it in the executeSql's 4th argument which is an error callback. This is intended behavior but is, in my experience, confusing.
同一事务回调中的语句然后确保它们都存在或考虑使用 DROP TABLE IF EXISTS 语法代替。如果在尝试删除时甚至一张表都不存在,则会导致整个事务失败。此失败会导致事务回滚,这意味着即使您认为数据应该被删除,数据仍将保留在您的数据库中。除非您在 executeSql 的第 4 个参数(错误回调)中专门监听它,否则不会报告任何错误。这是预期的行为,但根据我的经验,令人困惑。
回答by Prince V G
No method to delete the existing database in websql it will clear when the cache is cleared or
The browser is closed. If you want to create a database with the same name Just use openDatabase Method It will first check for the existence of the database with the same name. If not exists it will create one otherwise it will open the existing one
没有办法删除websql中已有的数据库,清空缓存或者
关闭浏览器都会清空。如果要创建同名数据库,只需使用 openDatabase 方法,它会首先检查是否存在同名数据库。如果不存在,它将创建一个,否则它将打开现有的
please follow this link http://html5doctor.com/introducing-web-sql-databases/
请点击此链接 http://html5doctor.com/introducing-web-sql-databases/