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

SQLite 一个超轻量级数据库,以娇小的“身材”,不失性能速度并具可靠性,而经久不衰,当前在数据库流行排行榜稳居前8位,它同样是一个开源关系型数据库,任何人可用于商业或非商业用途。跃使用的SQLite数据库超过1万亿, 最大支持DB大小为140 TB,执行文件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这都是为数据科学所提供的常用工具。更多功能自己可以去挖掘了。

打赏

wechatpay.jpg

ico-wechat.jpg微信扫一扫,打赏作者吧~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值