python程序连接mysql常用数据库
时间: 2024-05-10 16:16:44 浏览: 7
在 Python 中连接 MySQL 数据库,常用的数据库连接方式有两种:使用 MySQL 官方提供的 Python API(PyMySQL)或使用第三方库(例如 SQLAlchemy)。
下面是使用 PyMySQL 连接 MySQL 数据库的示例代码:
```
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost',
user='root',
password='password',
database='test')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("Database version : %s " % data)
# 关闭游标和数据库连接
cursor.close()
db.close()
```
上面的代码中,我们使用 `pymysql.connect()` 方法连接 MySQL 数据库,其中 `host`、`user`、`password` 和 `database` 是必需的参数。然后使用 `db.cursor()` 方法创建游标对象,执行 SQL 查询,最后关闭游标和数据库连接。
除了 PyMySQL,还可以使用其他 Python 连接 MySQL 数据库的库,例如 MySQL Connector、mysql-connector-python、mysqlclient 等。