在 Python 中操作 MySQL 数据库通常使用 `mysql-connector-python` 这个库,它提供了与 MySQL 数据库进行连接和交互的功能。下面是一些关于 Python 操作 MySQL 数据库的详细介绍和示例说明:
1. **连接到 MySQL 数据库**:
```python
import mysql.connector
# 建立数据库连接
mydb = mysql.connector.connect(
host="localhost",
user="username",
password="password",
database="dbname"
)
# 创建游标对象
mycursor = mydb.cursor()
```
2. **创建表格**:
```python
# 创建表格
mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
```
3. **插入数据**:
```python
# 插入数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit() # 确保数据提交
```
4. **查询数据**:
```python
# 查询数据
mycursor.execute("SELECT * FROM customers")
result = mycursor.fetchall()
for row in result:
print(row)
```
5. **更新数据**:
```python
# 更新数据
sql = "UPDATE customers SET address = 'Mountain 21' WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
```
6. **删除数据**:
```python
# 删除数据
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
mycursor.execute(sql)
mydb.commit()
```
7. **使用参数化查询**:
```python
# 参数化查询
sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Mountain 21", )
mycursor.execute(sql, adr)
result = mycursor.fetchall()
for row in result:
print(row)
```
以上是一些关于 Python 操作 MySQL 数据库的示例,展示了如何连接到数据库、创建表格、插入、查询、更新和删除数据,以及如何使用参数化查询。通过这些示例,您可以了解如何使用 Python 与 MySQL 数据库进行交互,执行常见的 SQL 操作。