如何以编程方式删除 WebSQL 中的数据库?

发布于 2024-12-01 10:02:50 字数 679 浏览 4 评论 0原文

我是Web SQL 数据库的新手,我使用它来将数据保存在网页的本地数据库中。

我可以创建一个数据库

var db = openDatabase('database', '1.0', 'my database', 2 * 1024 * 1024);

并且我可以创建 strong>表格 通过执行此操作,

db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS mytable (blah,blah)');
});

我可以删除表格

db.transaction(function (tx) {
  tx.executeSql('DROP TABLE mytable');
});

但是有没有办法删除数据库以编程方式?

I am new to Web SQL database and I use it to save data in a local database in a web page.

 I can create a database by

var db = openDatabase('database', '1.0', 'my database', 2 * 1024 * 1024);

 and I can create a table by doing this

db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS mytable (blah,blah)');
});

 I can delete the table by

db.transaction(function (tx) {
  tx.executeSql('DROP TABLE mytable');
});

 but is there a way to delete the database programmatically?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

旧城空念 2024-12-08 10:02:50

使用 PersistenceJS 有一个 persistence.reset API,它将清除数据库。
PersistenceJS站点

出于开发/测试目的,您可以通过搜索查看内容并删除webSQL、IndexedDB、cookie等对于您在 Chrome 中此 URL 的域名:

chrome://settings/cookies

您可以在其中删除某个域的所有存储或仅删除某些本地存储实体。是的,该 URL 仅意味着“cookie”,但该 URL 上的界面包括所有类型的离线存储。

我认为,如果 Chrome 开发人员工具界面能够右键单击并删除“资源”选项卡中的数据存储实体并检查内容,那就太好了。但目前,我所知道的只是设置/cookies URL。

Using PersistenceJS there is a persistence.reset API which will wipe the database clean.
PersistenceJS Site

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://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.

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.

国粹 2024-12-08 10:02:50

规范 说:

4.1 数据库

每个源都有一组关联的数据库。每个数据库都有一个名称和当前版本。 无法从此 API 枚举或删除可用于源的数据库。


Spec says:

4.1 Databases

Each origin has an associated set of databases. Each database has a name and a current version. There is no way to enumerate or delete the databases available for an origin from this API.

Bonjour°[大白 2024-12-08 10:02:50

我正在开发一个phonegap+jquery-mobile+KO应用程序,该应用程序具有离线存储功能,通过persistencejs使用web sql,并使用jasmine js进行BDD。

我正在研究某种“数据库清理器”,在每个规范之后执行。当我搜索如何删除 Web sql 数据库时,我阅读了回复 https://stackoverflow.com/a/10929725/667598< /a> (在此线程/问题中),然后查看该目录中的内容(Mac OS X)。

cd ~/Library/Application\ Support/Google/Chrome/Default/databases

在里面你会看到一个 Databases.db SQLite3 数据库,以及每个源的目录。这些目录以 protocol_host_somenumber 模式命名(我不知道那个数字是什么)。例如,就我而言,由于我的应用程序只是我在 Google Chrome 中使用 file:/// … 协议打开的文件,因此我可以看到 file__0 目录。对于 Twitter,我还可以看到 http_twitter.com_0 和 https_twitter.com_0。

在这个目录中,所有文件名都只是数字。例如,在 file__0 中,我找到了一个名为 8 的文件和另一个名为 9 的文件。在我的例子中,这些文件是 websql 数据库。我不知道chrome的Default/databases目录中是否也有索引数据库。

有了这个名字,就很难猜出数据库是什么。您可以打开数据库,然后必须通过其表格和数据推断应用程序或网站。

幸运的是,我之前提到的 Databases.db 是那些以数字命名的文件和数据库之间的映射。

您可以使用 sqlite3 命令打开 Databases.db 和任何其他 Web sql 文件。

sqlite3 Databases.db

显然,一旦进入 sqlite3 shell,掌握一些 SQL 知识就会很方便。不管怎样,一些帮助总是很方便的,可以通过命令获得。

.help

使用命令 .tables 您可以列出数据库中的表。在这个 Databases.db 中,我们可以找到数据库和元表。重要的是数据库,因此

select * from Databases;

我们可以看到数据库与其文件之间的映射。例如

7|http_jquerymobile.com_0|testdb|html5 测试数据库|200000

8|file__0|elfaro_dev|ElFaro desarrollo 数据基地|734003200

第一列是 id table 是用于数据库文件名的数字,第二个是源(目录),其他列是数据库名称、数据库从 Javascript API 创建数据库时使用的描述和估计大小。

因此,要实际删除数据库,我所做的就是从该表中删除它,例如:

delete from Databases where id = 8

然后从文件系统中删除实际文件(在 sqlite3 shell 之外)

rm file__0/8

就是这样。

PS:我知道对于一个简单的主题来说,这个答案太长了,但我只需要从我的系统中清除它并将其备份到某个地方,例如 SO 或博客。

I am developing a phonegap+jquery-mobile+KO app with offline storage using web sql via persistencejs, and jasmine js for BDD.

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).

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.

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.

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.

You can open the Databases.db and any other web sql file with the sqlite3 command

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

.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

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

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.

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)

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.

栩栩如生 2024-12-08 10:02:50

开发人员选项

目前还无法以编程方式枚举或删除数据库。
Chrome 开发者可以导航至 chrome://settings/cookies 搜索并删除任何数据库
Opera 开发人员可以导航到 opera://settings/cookies

真正删除数据库(以及其他所有内容)的唯一方法

新的 Spec 表示这可能在具有响应标头和 JavaScript 的功能中实现。
缺点是您无法控制要删除的内容,因此您需要首先创建备份,除非您想清除所有内容

2.1.3。存储参数

存储参数指示服务器希望删除与特定响应 URL 的来源相关的本地存储数据。这包括存储机制,例如(localStorage、sessionStorage、[INDEXEDDB]、[WEBDATABASE] 等),以及切线相关的机制,例如服务工作者注册。

Js:

navigator.storage.clear({
    types: [ "storage" ],
    includeSubdomains: true // false by default
});

响应标头:

res.header("Clear-Site-Data", "storage; includeSubdomains");

但这不适用于任何浏览器...

客户端(而不是开发人员)的最佳解决

/* 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);
    });

}

方案

dropDatabase("database", function(){
    console.log("done")
});

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

The only way to truly delete a database (and everything else)

A new Spec says this might be possible in the feature with both response header and javascript.
The disadvantages is 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

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.

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")
});
如若梦似彩虹 2024-12-08 10:02:50

本地数据库文件存储在 Windows 用户设置中的“应用程序数据”>“应用程序数据”下。谷歌>铬>用户数据>默认>数据库。

所以手动删除它们理论上是可以的。这仅在您自己的计算机上测试/开发时有用,因为当其他用户打开您的应用程序/站点时,它不太可能具有文件系统访问权限。

但是,即使您可以找到这些文件并将其删除,数据也会保留下来。我已经尝试过打开和关闭 Chrome,并且所有 chrome 进程都已结束,但浏览器检查器不断向我显示我的旧数据库,其中包含所有不需要的字段和数据。

The localdatabase files are stored in your Windows user settings under Application Data > Google > Chrome > User Data > Default > databases.

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.

故事未完 2024-12-08 10:02:50

HTML5 数据库存储(SQL lite) - 几个问题对此进行了解答。

总结一下:

  • 目前无法删除 WebSQL 数据库。
  • 可能使用 Indexed DB 或 localStorage 代替。

This is answered in HTML5 database storage (SQL lite) - few questions.

To summarize:

  • Currently no way to drop a WebSQL database.
  • Probably use Indexed DB or localStorage instead.
北座城市 2024-12-08 10:02:50

我的库 实现中,我只是删除所有表。这确实删除了数据库。表列表是select * from sqlite_master

In my library implementation, I just delete all tables. Which, indeed, delete the database. List of tables are select * from sqlite_master.

愛上了 2024-12-08 10:02:50

请注意,如果您在同一事务回调中使用多个

tx.executeSql('DROP TABLE mytable'); 

语句,请确保它们全部存在或考虑使用 DROP TABLE IF EXISTS 语法。当您尝试删除时,即使有一张表不存在,也会导致整个事务失败。此失败会导致事务回滚,并且意味着即使您认为应该删除数据,数据也会保留在数据库中。除非您在executeSql 的第四个参数(错误回调)中专门监听它,否则不会报告错误。这是预期的行为,但根据我的经验,这是令人困惑的。

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.

风苍溪 2024-12-08 10:02:50

没有方法删除websql中现有的数据库,它会在清除缓存时清除或
浏览器已关闭。如果要创建同名数据库只需使用 openDatabase 方法,它会首先检查是否存在同名数据库。如果不存在,它将创建一个,否则它将打开现有的数据库,

请点击此链接 http:// html5doctor.com/introducing-web-sql-databases/

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

please follow this link http://html5doctor.com/introducing-web-sql-databases/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文