用python3.6编写代码,一个方法完成获取mysql、pgsql、oracle、kingbase、mariadb、hive数据库的连接
时间: 2023-10-20 08:05:38 浏览: 133
下面是 Python3.6 的代码示例,可以连接 MySQL、PostgreSQL、Oracle、Kingbase、MariaDB 和 Hive 数据库:
```python
import pymysql
import psycopg2
import cx_Oracle
import pykingbase
import mariadb
from pyhive import hive
def get_db_connection(database_type, host, port, username, password, database_name):
if database_type == 'mysql':
connection = pymysql.connect(
host=host,
port=port,
user=username,
password=password,
db=database_name
)
elif database_type == 'pgsql':
connection = psycopg2.connect(
host=host,
port=port,
user=username,
password=password,
database=database_name
)
elif database_type == 'oracle':
connection = cx_Oracle.connect(
username,
password,
f'{host}:{port}/{database_name}'
)
elif database_type == 'kingbase':
connection = pykingbase.connect(
host=host,
user=username,
password=password,
port=port,
database=database_name
)
elif database_type == 'mariadb':
connection = mariadb.connect(
user=username,
password=password,
host=host,
port=port,
database=database_name
)
elif database_type == 'hive':
connection = hive.connect(
host=host,
port=port,
username=username,
password=password,
database=database_name,
auth='NOSASL'
)
else:
raise ValueError(f"Unsupported database type '{database_type}'")
return connection
```
以上是一个 Python 方法,可以根据指定的数据库类型、IP 地址、用户名、密码等参数来连接 MySQL、PostgreSQL、Oracle、Kingbase、MariaDB 和 Hive 数据库。根据不同的数据库类型调用相应的库来进行连接。
阅读全文