python对数据库增删改查
时间: 2023-10-02 17:12:31 浏览: 93
python界面实现数据库增删改查
4星 · 用户满意度95%
Python可以使用不同的库来连接和操作数据库,以下是使用Python对MySQL数据库进行增删改查的示例:
1. 连接数据库
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
```
2. 插入数据
```python
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
```
3. 查询数据
```python
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
4. 更新数据
```python
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
```
5. 删除数据
```python
mycursor = mydb.cursor()
sql = "DELETE FROM customers WHERE address = 'Canyon 123'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
```
以上是使用Python对MySQL数据库进行增删改查的示例,其他类型的数据库操作也类似,只需根据具体的数据库和库的Python接口进行相应的调整。
阅读全文