# 连接MySQL(应急库)和PL/SQL(生产库) conn_mysql = pymysql.connect(...) conn_oracle = connect_to_oracle('...')给出示例
时间: 2024-10-08 20:14:34 浏览: 30
这里有两个连接数据库的例子,分别连接到MySQL(使用pymysql模块)和Oracle数据库(假设使用的是cx_Oracle模块):
1. **连接MySQL(使用pymysql)**:
```python
import pymysql
# 参数替换为实际的数据库连接配置
config_mysql = {
'host': 'your_host',
'user': 'your_username',
'password': 'your_password',
'db': 'your_database'
}
try:
conn_mysql = pymysql.connect(**config_mysql)
except pymysql.MySQLError as e:
print(f"Failed to connect to MySQL: {e}")
else:
print("Connected to MySQL")
```
2. **连接Oracle(使用cx_Oracle)**:
```python
import cx_Oracle
# 参数替换为实际的Oracle连接字符串
config_oracle = {
'dsn': 'YOUR_DSN_STRING', # 例如:(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname)(PORT=port))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=servicename)))
'username': 'your_username',
'password': 'your_password'
}
try:
conn_oracle = cx_Oracle.connect(user=config_oracle['username'], password=config_oracle['password'], dsn=config_oracle['dsn'])
except cx_Oracle.DatabaseError as e:
print(f"Failed to connect to Oracle: {e}")
else:
print("Connected to Oracle")
```
这两个例子展示了如何利用Python的不同库(pymysql for MySQL,cx_Oracle for Oracle)建立数据库连接。每个连接函数都捕获了相应的错误,并打印错误信息。
阅读全文