python 读取数据库

这篇博客介绍了两种Python连接数据库并执行查询的方法。第一种使用pyhive库连接Hive数据库,将查询结果转换为DataFrame。第二种通过pymysql库读取配置文件,建立MySQL连接,利用read_sql获取DataFrame数据。作者推荐了使用配置文件的方式,因为它更方便。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.连接数据库,并执行查询语句,返回查询结果,并转成dataframe形式

import numpy as np
import pandas as pd
from operator import itemgetter
import matplotlib.pyplot as plt

import requests
import pandas as pd
import json
from pyhive import hive
import time
import re

def init_hive_connect(db= dbname):
    """
    init hive connect
    :param db: db name
    :return: hive connect object
    """
    hive_conn = hive.Connection(
        host        = db_host,
        port        = db_port,
        username    = user_name,
        password    = user_pw,
        auth        = "LDAP",
        database    = data_base
    )
    return hive_conn

def hive_query(hive_conn,sql):
    """
    query
    :param sql: exec sql
    :return: sql result
    """
    with hive_conn.cursor() as cursor:
        cursor.execute(sql)
        return cursor.fetchall()
    
def get_data(hive_sql):
    hive_conn = init_hive_connect()
    hive_res = hive_query(hive_conn,hive_sql)
    return hive_res


hive_sql = ''''''
res = get_data(hive_sql)
data = pd.DataFrame(list(res),columns=col_name)

2.使用传参方式

config内容

[data]
host=host_name
user=user_name
passwd=pw
port=port_num
db=db_name
charset=utf8

读取sql

import pymysql
from configparser import ConfigParser
cp = ConfigParser()
cp.read("db.fcg")
cp.sections()
db_para = cp['data']

db_conn = pymysql.connect(host=db_para['host'], port=int(db_para['port']), user=db_para['user'], passwd=db_para['passwd'], db=db_para['db'], charset=db_para['charset'])     #建立连接

sql = ''''''

res_info = pd.read_sql(sql, db_conn_)  #返回 dataframe格式数据

以上两种方式供大家选择(相比之下我更喜欢第二种方式)。

关于configparser模块,可以参考这里:https://blog.youkuaiyun.com/csdn_kelly/article/details/113661989

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值