简体   繁体   English

使用Python读取SQLite文件

[英]Reading a SQLite file using Python

I am working on an assignment where in we were provided a bunch of csv files to work on and extract information . 我正在做一个作业,为我们提供了一堆csv文件来处理和提取信息。 I have succesfuly completed that part. 我已经成功完成了这一部分。 As a bonus question we have 1 SQlite file with a .db extension . 作为一个额外的问题,我们有1个SQlite文件, .db名为.db I wanted to know if any module exists to convert such files to .csv or to read them directly ? 我想知道是否存在将这些文件转换为.csv或直接读取它们的模块?

In case such a method doesnt exist , ill probably insert the file into a database and use the python sqlite3 module to extract the data I need. 如果这种方法不存在,可能会将文件插入数据库并使用python sqlite3模块提取我需要的数据。

You can use the sqlite commandline tool to dump table data to CSV. 您可以使用sqlite命令行工具将表数据转储为CSV。

To export an SQLite table (or part of a table) as CSV, simply set the "mode" to "csv" and then run a query to extract the desired rows of the table.

sqlite> .header on
sqlite> .mode csv
sqlite> .once c:/work/dataout.csv
sqlite> SELECT * FROM tab1;

In the example above, the " .header on " line causes column labels to be printed as the first row of output. 在上面的示例中,“。 header on行使列标签被打印为输出的第一行。 This means that the first row of the resulting CSV file will contain column labels. 这意味着结果CSV文件的第一行将包含列标签。 If column labels are not desired, set ".header off" instead. 如果不需要列标签,请改为设置“ .header off”。 (The ".header off" setting is the default and can be omitted if the headers have not been previously turned on.) (“ .header off”设置是默认设置,如果以前未打开过标题,则可以省略。)

The line " .once FILENAME " causes all query output to go into the named file instead of being printed on the console. .once FILENAME行使所有查询输出进入命名文件,而不是打印在控制台上。 In the example above, that line causes the CSV content to be written into a file named "C:/work/dataout.csv". 在上面的示例中,该行导致将CSV内容写入名为“ C:/work/dataout.csv”的文件中。

http://www.sqlite.org/cli.html http://www.sqlite.org/cli.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM