首页 » 开发语言 » Python中内置了数据库?SQLite3 (苔花如米小,也学牡丹开)

Python中内置了数据库?SQLite3 (苔花如米小,也学牡丹开)

SQLite 一个超轻量级数据库,以娇小的“身材”,不失性能速度并具可靠性,而经久不衰,当前在数据库流行排行榜稳居前8位,它同样是一个开源关系型数据库,任何人可用于商业或非商业用途,它几乎存在于所有智能手机(iOS 和 Android)、计算机、网络浏览器、电视和汽车中。跃使用的SQLite数据库超过1万亿, 最大支持DB大小为140 TB,SQLite是一个单节点和(大部分)单线程在线事务处理(OLTP)数据库。它有一个进程内/嵌入式设计,以及一个独立的(无依赖关系)代码库……由 150K 行代码组成的单个 C 库。启用所有功能后,编译后的库大小可以小于 750 KiB。然而,SQLite每秒可以支持数以万计的事务。当前版本执行文件2-3MB,单文件无需配置的数据库,但支持SQL和关系型数据库常见的基本功能。如果你是搞开发可能不会陌生,  如果你是使用Python做开发或运维,更应该知道她,常用于嵌入式、物联网、内部测试、演示、数据科学、传输等用途。

最重要的是, SQLite实际上是作为Python库内置的。换句话说,您不需要安装任何服务器端/客户端软件,也不需要保持某些东西作为服务运行,只要您使用Python导入了该库并开始编码,那么您就可以有一个关系数据库管理系统!

下面演示一下使用

import sqlite3 as sl
import pandas as pd
# create db in filesystem
#conn = sl.connect('my-test.db')
# create db in memory 
conn = sl.connect(':memory:')
# Create a table
with conn:
    # conn.execute("""
    #      drop table events;
    #  """)
    conn.execute(
  'CREATE TABLE events(ts, msg, PRIMARY KEY(ts, msg))')
try:
# Insert values
    with conn:
        conn.executemany('INSERT INTO events VALUES (?, ?)', [
            (1, 'foo'),
            (2, 'bar'),
            (3, 'baz'),
            (5, 'foo'),
        ])
except (sl.OperationalError, sl.IntegrityError) as e:
    print('Could not complete operation:', e)
# No row was inserted because transaction failed
for row in conn.execute('SELECT * FROM events'):
# Print inserted rows
    print(row)


PS D:\code\EchartsShow> & D:/Python/Python38/python.exe d:/code/EchartsShow/testsqlite.py
(1, 'foo')
(2, 'bar')
(3, 'baz')
(5, 'foo')

更重要的是可以配合pandas 做数据科学分析

df_skill = pd.DataFrame({
    'user_id': [1,1,2,2,3,3,3],
    'skill': ['Network Security', 'Algorithm Development', 'Network Security', 'Java', 'Python', 'Data Science', 'Machine Learning']
})

# call to_sql() method of the data frame to save it into the database.
df_skill.to_sql('SKILL', conn)

# join tables 
df = pd.read_sql('''
    SELECT s.user_id, u.ts, u.msg, s.skill 
    FROM events u LEFT JOIN SKILL s ON u.ts = s.user_id
''', conn)

print(df)

# save join result to new table
df.to_sql('events_SKILL', conn)

# close connection
conn.close()

PS D:\code\EchartsShow> & D:/Python/Python38/python.exe d:/code/EchartsShow/testsqlite.py
(1, 'foo')
(2, 'bar')
(3, 'baz')
(5, 'foo')
   user_id  ts  msg                  skill
0      1.0   1  foo  Algorithm Development
1      1.0   1  foo       Network Security
2      2.0   2  bar                   Java
3      2.0   2  bar       Network Security
4      3.0   3  baz           Data Science
5      3.0   3  baz       Machine Learning
6      3.0   3  baz                 Python
7      NaN   5  foo                   None

可以直接生成Pandas Data Frame或存入SQLite数据库,当然支持关连、增、删、改、查都没问题。 PYTHON、SQL、PANDAS这都是为数据科学所提供的常用工具。更多功能自己可以去挖掘了。

打赏

, ,

对不起,这篇文章暂时关闭评论。