Python 操作mysql
时间: 2023-06-28 13:06:05 浏览: 121
在 Python 中操作 MySQL 数据库需要使用 MySQL 官方提供的 Python 驱动程序——MySQL Connector/Python。以下是一个简单的示例:
1. 安装 MySQL Connector/Python
使用 pip 命令安装 MySQL Connector/Python:
```
pip install mysql-connector-python
```
2. 连接 MySQL 数据库
使用以下代码连接 MySQL 数据库:
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
print(mydb)
```
3. 创建数据库表
使用以下代码创建一个名为 customers 的表:
```python
mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))")
```
4. 插入数据
使用以下代码向 customers 表中插入一条数据:
```python
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
```
5. 查询数据
使用以下代码查询 customers 表中的所有数据:
```python
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
这是一个基本的操作示例,你可以根据自己的需求进行更加详细和复杂的操作。
阅读全文
相关推荐











