Python+Pandas:快速连接各种常用数据库满足你的一切常用需求
在大数据时代下,和数据打打交道是家常便饭。那么常用储存数据的一种方式:数据库,用起来那也是相当的得心应手,今天就用python连接各类常见数据库!
常用数据库
1.sqlite
非常轻量的关系型数据库,不需要安装服务端,解压即用
import sqlite3import 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 pdfrom 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 pdfrom 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 MongoClientimport pandas as pd client = MongoClient('localhost', 27017)collection = client['test']['user']data = collection.find()df = pd.DataFrame(list(data))print(df)
5.redis
缓存数据库,快,并且支持五大数据类型
import asynciofrom aredis import StrictRedisasync 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 pdfrom 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()
目录 返回
首页