python连接mysql、oracle数据库

发布时间 2023-12-06 21:49:24作者: EPIHPANY

python版本:3.10.5
mysql版本: 8.0.27
oracle版本:oracle 12c

一、python连接mysql数据库

  1. 安装第三方依赖PyMySQL, 终端执行如下命令:
pip install PyMySQL
  1. PyMySQL使用
import pymysql

config = {
        'host': '127.0.0.1',
        'port': 3306,
        'user': 'root',
        'password': 'root',
        'database': 'mysql',
}
# 获取连接
connection = pymysql.connect(**config)
# 获取游标
cursor = connection.cursor()
# 执行sql
cursor.execute("select now() from dual")
# 提取结果
print(cursor.fetchone())
# 关闭资源
cursor.close()
connection.close()

# 使用with语句可以不用手动关闭资源
with pymysql.connect(**config) as conn:
    with conn.cursor() as cur:
        cur.execute("select now() from dual")
        print(cur.fetchone())

二、python链接oracle数据库

  1. 安装第三方依赖oracledb (cx_oracle),终端执行如下命令:
pip install oracledb

官方文档:https://python-oracledb.readthedocs.io/en/latest/user_guide/installation.html
2. oracledb使用

import oracledb

config = {
    'user': 'system',
    'dsn': '127.0.0.1:1521/orcl',
    'password': '123456'
}

with oracledb.connect(**config) as connection:
    with connection.cursor() as cursor:
        cursor.execute("select sysdate from dual")
        print(cursor.fetchone())