使用Python连接数据库,并实现增、删、改、查等操作
时间: 2023-07-10 07:15:21 浏览: 48
好的,下面是使用Python连接数据库并实现增、删、改、查操作的示例代码,以MySQL为例:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
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, "记录插入成功。")
# 查询数据
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# 更新数据
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "记录被修改。")
# 删除数据
sql = "DELETE FROM customers WHERE address = 'Canyon 123'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "记录被删除。")
```
以上代码中,我们使用`mysql.connector`库连接到MySQL数据库,并执行了插入、查询、更新、删除等操作。您可以根据具体的需求进行调整和完善。