要使用Python连接Oracle、MySQL和PostgreSQL数据库,可以使用cx_Oracle
、mysql-connector-python
和psycopg2
这三个库。
首先,确保你已经安装了这些库。如果没有安装,可以使用pip安装:
pip install cx_Oracle mysql-connector-python psycopg2
以下是连接每种数据库的示例代码:
Oracle:
import cx_Oracle
connection = cx_Oracle.connect('username/password@localhost/orcl')
cursor = connection.cursor()
# 执行查询
cursor.execute('SELECT * FROM your_table')
for row in cursor:
print(row)
# 关闭连接
cursor.close()
connection.close()
MySQL:
import mysql.connector
connection = mysql.connector.connect(
host='localhost',
user='username',
password='password',
database='your_database'
)
cursor = connection.cursor()
# 执行查询
cursor.execute('SELECT * FROM your_table')
for row in cursor:
print(row)
# 关闭连接
cursor.close()
connection.close()
PostgreSQL:
import psycopg2
connection = psycopg2.connect(
dbname='your_database',
user='username',
password='password',
host='localhost',
port='5432'
)
cursor = connection.cursor()
# 执行查询
cursor.execute('SELECT * FROM your_table')
for row in cursor:
print(row)
# 关闭连接
cursor.close()
connection.close()
请确保替换示例代码中的用户名、密码、数据库名称和表名以连接到你的数据库并执行相应的查询。