数据库的增删查改如何用代码实现
时间: 2024-05-02 12:17:20 浏览: 55
php实现数据库的增删改查
5星 · 资源好评率100%
数据库的增删查改是数据库最常用的四种操作,通常使用 SQL 语句进行实现。下面是使用 Python 语言和 MySQL 数据库进行增删查改的示例代码:
1. 连接数据库
```python
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
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()
print(mycursor.rowcount, "record inserted.")
```
3. 查询数据
```python
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
4. 更新数据
```python
sql = "UPDATE customers SET address = 'Canyon 123' WHERE address = 'Highway 21'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
```
5. 删除数据
```python
sql = "DELETE FROM customers WHERE address = 'Canyon 123'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
```
以上示例代码仅供参考,实际应用中需要根据具体情况进行修改。
阅读全文