在大資料時代下,和資料打打交道是家常便飯,那么常用儲存資料的一種方式:資料庫,用起來那也是相當的得心應手,今天就用python連接各類常見資料庫!
常用資料庫
- 1.sqlite
- 2.mysql
- 3.postgresql
- 4.mongodb
- 5.redis
- 6.hive
- 7.clickhouse
- 8.habse
1.sqlite
非常輕量的關系型資料庫,不需要安裝服務端,解壓即用

import sqlite3
import pandas as pd
conn = sqlite3.connect('test.db')
df = pd.read_sql_query('select * from company', con=conn)
print(df)

2.mysql
最受歡迎、使用最多的關系型資料庫之一
import pandas as pd
from sqlalchemy import create_engine
mysql_url = 'mysql+pymysql://root:root@localhost:3306/test?charset=utf8'
engine = create_engine(mysql_url)
data = pd.read_sql_table('user1', engine)
print(data)

3.postgresql
物件關系型資料庫,開源人士自行研發的資料庫

import pandas as pd
from sqlalchemy import create_engine
postgres_url = 'postgres://postgres:root@localhost:5432/db1'
engine = create_engine(postgres_url)
data = pd.read_sql_table('company', engine)
print(data)

4.mongodb
檔案型資料庫,將資料已一個個json檔案格式進行存盤
from pymongo import MongoClient
import pandas as pd
client = MongoClient('localhost', 27017)
collection = client['test']['user']
data = collection.find()
df = pd.DataFrame(list(data))
print(df)

5.redis
快取資料庫,快,并且支持五大資料型別
import asyncio
from aredis import StrictRedis
async def example():
client = StrictRedis(host='127.0.0.1', port=6379, db=0)
await client.flushdb()
uid = await client.get('id')
uname = await client.get('name')
uage = await client.get('age')
print(f'user:id={uid},name={uname},age={uage}')
loop = asyncio.get_event_loop()
loop.run_until_complete(example())
loop.close()

6.hive
資料倉庫工具,可以把HDFS上的結構化資料映射成表,以供查詢
import pandas as pd
from pyhive import hive
conn = hive.Connection(
host='localhost',
port=10000,
database='test',
username='hive',
password=''
)
data = pd.read_sql_query('select * from test', con=conn)
print(data)
7.clickhouse
列示存盤資料庫,可用于構建在hive之上的一個在線查詢分析,為了彌補hive查詢速度慢的劣勢,我們公司已經在用了
from clickhouse_driver import Client
client = Client(host='127.0.0.1', port='9000', user='ck_user', password='ck_pass')
sql = 'select * from db_name.tb_name limit 0, 10'
ans = client.execute(sql)
8.habse
也是列示存盤資料庫,通過rowkey,類似于主鍵來查詢資料,能夠因對超大資料的挑戰
import happybase
connection = happybase.Connection('localhost', autoconnect=False)
connection.open()
print(connection.tables())
connection.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/352151.html
標籤:其他
下一篇:Flink學習記錄--入門篇



