Python使用MySQL数据库进行增删改查操作的语句
时间: 2024-03-22 08:37:17 浏览: 76
好的,以下是Python使用MySQL数据库进行增删改查操作的语句示例:
1. 连接MySQL数据库:
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
mycursor = mydb.cursor()
```
2. 插入数据:
```python
sql = "INSERT INTO yourtable (column1, column2, column3) VALUES (%s, %s, %s)"
val = ("value1", "value2", "value3")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
```
3. 查询数据:
```python
mycursor.execute("SELECT * FROM yourtable")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
4. 更新数据:
```python
sql = "UPDATE yourtable SET column1 = %s WHERE column2 = %s"
val = ("newvalue", "oldvalue")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
```
5. 删除数据:
```python
sql = "DELETE FROM yourtable WHERE column1 = %s"
val = ("value")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
```
以上就是Python使用MySQL数据库进行增删改查操作的语句示例,希望对你有帮助。
阅读全文