当前位置:Gxlcms > 数据库问题 > Python读取和处理文件后缀为".sqlite"的数据文件

Python读取和处理文件后缀为".sqlite"的数据文件

时间:2021-07-01 10:21:17 帮助过:25人阅读

sqlite3 with sqlite3.connect(‘test_database.sqlite‘) as con: c = con.cursor() c.execute(‘‘‘CREATE TABLE test_table (date text, city text, value real)‘‘‘) for table in c.execute("SELECT name FROM sqlite_master WHERE type=‘table‘"): print("Table", table[0]) c.execute(‘‘‘INSERT INTO test_table VALUES (‘2017-6-25‘, ‘bj‘, 100)‘‘‘) c.execute(‘‘‘INSERT INTO test_table VALUES (‘2017-6-25‘, ‘pydataroad‘, 150)‘‘‘) c.execute("SELECT * FROM test_table") print(c.fetchall())
Table test_table
[(‘2017-6-25‘, ‘bj‘, 100.0), (‘2017-6-25‘, ‘pydataroad‘, 150.0)]

关于SQLite数据库中数据的可视化预览,有很多的工具可以实现,我这里使用的是SQLite Studio,是一个免费使用的工具,不需要安装,下载下来就可以使用,有兴趣的同学可以参考下面的链接。

https://sqlitestudio.pl/index.rvt?act=download

数据预览的效果如下:

技术分享

技术分享

用pandas来读取sqlite数据文件

从上面代码的运行结果可以看出,数据查询的结果是一个由tuple组成的list。python的list数据在进行进一步的数据处理与分析时,可能会不太方便。可以想象一下,假设如果数据库的表格中一共有100万行或者更多数据,从list中循环遍历获取数据,效率会比较低。

这时,我们可以考虑用pandas提供的函数来从SQLite数据库文件中读取相关数据信息,并保存在DataFrame中,方便后续进一步处理。

Pandas提供了两个函数,均可以读取后缀为“.sqlite”数据文件的信息。

  • read_sql()
  • read_sql_query()
import pandas as pd

with sqlite3.connect(‘test_database.sqlite‘) as con:

    # read_sql_query和read_sql都能通过SQL语句从数据库文件中获取数据信息
    df = pd.read_sql_query("SELECT * FROM test_table", con=con)
    # df = pd.read_sql("SELECT * FROM test_table", con=con)

    print(df.shape)
    print(df.dtypes)
    print(df.head())
(2, 3)
date      object
city      object
value    float64
dtype: object
        date        city  value
0  2017-6-25          bj  100.0
1  2017-6-25  pydataroad  150.0


技术分享
?

Python读取和处理文件后缀为".sqlite"的数据文件

标签:overflow   项目   blog   建立连接   方便   步骤   aop   where   connect   

人气教程排行