python连接数据库

记录几种常见的python连接数据库的代码,方便用的时候直接取。

1.python连接mysql

import pymysql
import pprint
#
# HOST = '127.0.0.1'
# PORT = 3306
# USER = 'root'
# PASSWD = 'root'
# dbName = 'mysql'


def conn_mysql(host,port,user,passwd,dbname):
    conn = pymysql.connect(host=host,
                           port=port,
                           user=user,
                           passwd=passwd,
                           db=dbname,
                           charset='utf8')
    cursor = conn.cursor()

    # def show_tables():
    sql = 'show tables;'
    cursor.execute(sql)
    rowList = cursor.fetchall()
    tableList = list()
    for row in rowList:
        tableList.append(row[0])
    print('tableList(%d):\n%s\n' % (len(tableList), pprint.pformat(tableList, indent=4)))
    # return tableList

2.python连接hive

from pyhive import hive
import pandas as pd
ip=''
conn = hive.connect(ip)
def runhql(sql):
    cursor = conn.cursor()
    cursor.execute(sql)
    logs = cursor.fetch_logs()
    datas = cursor.fetchall()
    print(len(datas))
    return datas

3.python连接德鲁伊库

from pydruid.db import connect
def find_druid(ip,port,sql):  
    conn = connect(host=ip, port=port)  
    curs = conn.cursor()
    curs.execute(sql)
    df = pd.DataFrame(curs.fetchall())
    return df

4.python连接sqlsever

import pymssql
import pprint

def conn_sqlserver(host,port,user,password,database):
    port = str(port)
    host = host+':'+port
    connect = pymssql.connect(host=host, user=user, password=password,
                              database=database, charset='utf8')
    if connect:
        print("连接成功!")
    cursor = connect.cursor()  # 创建一个游标对象,python里的sql语句都要通过cursor来执行
    cursor.execute("select name from sysobjects where xtype='U'")  # 执行sql语句,获取数据库中的表名
    rowList = cursor.fetchall()
    tableList = []
    for row in rowList:
        tableList.append(row[0])
    print('tableList(%d):\n%s\n' % (len(tableList), pprint.pformat(tableList, indent=4)))

    # 处理每个表
    for tabName in tableList:
        print('table %s ...' % tabName)
        sql = "select name from syscolumns where id = object_id('%s')"
        sql = sql % (tabName)
        cursor.execute(sql)
        rowList = cursor.fetchall()
        fieldList = list()
        for row in rowList:
            fieldList.append(row[0])
        print('fieldList(%d):\n%s\n' % (len(fieldList), pprint.pformat(fieldList, indent=4)))
    cursor.close()  # 关闭游标
    connect.close()  # 关闭连接

5.python连接oracle

import cx_Oracle
import pprint

def conn_oracle(host,port,user,passwd,dbname,sql):
    port = str(port)
    host_port = user+'/'+passwd+'@'+host+':'+port+'/'+dbname
    conn = cx_Oracle.connect("%s" %host_port)
    cursor = conn.cursor()

    # 获取当前用户下的所有表的信息
    # def conn_oracle():
    results = cursor.execute(sql)
    # 获取所有数据
    all_data = cursor.fetchall()
    tabList = []
    for data in all_data:
        tabList.append(data[0])
    print('tabList(%d):\n%s\n' % (len(tabList), pprint.pformat(tabList, indent=4)))

    # 处理每个表
    for tabName in tabList:
        print('table %s ...' % tabName)
        sql = 'select * from "%s" '
        sql = sql % (tabName)
        cursor.execute(sql)
        rowList = cursor.fetchall()
        title = [i[0] for i in cursor.description]
        print(title)
        # fieldList = list()
        # for row in rowList:
        #     fieldList.append(row[0])
        # print('fieldList(%d):\n%s\n' % (len(fieldList), pprint.pformat(fieldList, indent=4)))
    cursor.close()
    conn.close()

6.python 连接impala查询:

        

from impala.dbapi import connect
ip=''
port=''
sql=''
conn = connect(host=ip, port=port)
cur = conn.cursor()
cur.execute(sql)
data_list=cur.fetchall()
for data in data_list:
   print data

  • 1
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中,使用SQLAlchemy或pymysql等库连接数据库并创建表是非常常见的任务。这里我们以SQLite(内置数据库)和SQLAlchemy为例来说明,其他如MySQL、PostgreSQL等数据库略有不同但基本原理相似。 **使用SQLite和SQLAlchemy:** 首先,你需要安装SQLAlchemy库(如果还没有安装): ```bash pip install sqlalchemy ``` 然后,你可以创建一个SQLite连接并定义表结构: ```python from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base # 创建基础模型 Base = declarative_base() # 定义表名和字段 class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(50), nullable=False) email = Column(String(120), unique=True) # 创建数据库引擎 engine = create_engine('sqlite:///example.db') # 创建表 Base.metadata.create_all(engine) ``` **使用pymysql连接MySQL:** 首先,安装pymysql库: ```bash pip install pymysql ``` 然后使用如下代码创建连接并创建表: ```python import pymysql # 创建连接 connection = pymysql.connect(host='localhost', user='your_username', password='your_password', db='your_database') # 创建游标 cursor = connection.cursor() # 定义SQL语句 create_table_query = """ CREATE TABLE IF NOT EXISTS users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50) NOT NULL, email VARCHAR(120) UNIQUE ) """ # 执行SQL cursor.execute(create_table_query) connection.commit() # 关闭游标和连接 cursor.close() connection.close() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值