python使用MySQL数据库进行增删改查操作的语句
时间: 2024-03-21 18:42:41 浏览: 60
好的,以下是Python使用MySQL数据库进行增删改查操作的语句示例:
1. 连接MySQL数据库:
```python
import mysql.connector
# 建立数据库连接
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="mydatabase"
)
# 创建游标对象
mycursor = mydb.cursor()
```
2. 插入数据:
```python
# 插入单条数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
# 插入多条数据
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = [
('Peter', 'Lowstreet 4'),
('Amy', 'Apple st 652'),
('Hannah', 'Mountain 21'),
('Michael', 'Valley 345'),
('Sandy', 'Ocean blvd 2'),
('Betty', 'Green Grass 1'),
('Richard', 'Sky st 331'),
('Susan', 'One way 98'),
('Vicky', 'Yellow Garden 2'),
('Ben', 'Park Lane 38'),
('William', 'Central st 954'),
('Chuck', 'Main Road 989'),
('Viola', 'Sideway 1633')
]
mycursor.executemany(sql, val)
mydb.commit()
```
3. 查询数据:
```python
# 查询所有数据
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# 查询指定数据
sql = "SELECT * FROM customers WHERE address = %s"
adr = ("Yellow Garden 2", )
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
4. 更新数据:
```python
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Valley 345'"
mycursor.execute(sql)
mydb.commit()
```
5. 删除数据:
```python
sql = "DELETE FROM customers WHERE address = 'Mountain 21'"
mycursor.execute(sql)
mydb.commit()
```
阅读全文