要使用Python连接MySQL数据库,你可以选择使用`mysql-connector-python`或`PyMySQL`库。以下是使用这两种库连接MySQL数据库的步骤:
使用`mysql-connector-python`
1. 安装库:
```bash
pip install mysql-connector-python
2. 连接数据库的示例代码:
```python
import mysql.connector
try:
连接到MySQL数据库
connection = mysql.connector.connect(
host='localhost', 数据库主机地址
database='test_db', 数据库名称
user='your_username', 数据库用户名
password='your_password' 数据库密码
)
if connection.is_connected():
print('成功连接到数据库')
cursor = connection.cursor()
创建表(如果不存在)
cursor.execute('CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50), age INT)')
插入数据
cursor.execute("INSERT INTO users (name, age) VALUES (%s, %s)", ('小王', 25))
提交事务
connection.commit()
关闭游标和连接
cursor.close()
connection.close()
except Error as e:
print(f"连接失败: {e}")
使用`PyMySQL`
1. 安装库:
```bash
pip install pymysql
2. 连接数据库的示例代码:
```python
import pymysql
建立数据库连接
conn = pymysql.connect(
host='localhost', 数据库主机名
user='your_username', 数据库用户名
password='your_password', 数据库密码
database='your_database', 要连接的数据库名
charset='utf8mb4' 设置字符集,防止中文乱码
)
try:
with conn.cursor() as cursor:
创建表
create_table = '''
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT
)
'''
cursor.execute(create_table)
插入数据
sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
cursor.execute(sql, ('小王', 25))
提交事务
conn.commit()
获取单条数据
data = cursor.fetchone()
print(f"Database version: {data}")
except Exception as e:
print(f"连接失败: {e}")
finally:
关闭连接
conn.close()
请确保在尝试连接之前,MySQL服务器已经安装并运行,并且创建了一个数据库用户。