使用python插入\更新mysql
时间: 2023-10-24 07:08:13 浏览: 36
可以使用Python中的MySQL Connector模块来实现MySQL数据库的插入和更新操作。以下是一个示例代码:
```python
import mysql.connector
# 连接MySQL数据库
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, "record inserted.")
# 更新数据
sql = "UPDATE customers SET address = 'Canyon 123' WHERE name = 'John'"
mycursor.execute(sql)
# 提交更改
mydb.commit()
# 输出更新的数据行数
print(mycursor.rowcount, "record(s) affected.")
```
在这个例子中,我们连接到了名为 `yourdatabase` 的数据库,并在其中的 `customers` 表中插入了一行数据,然后更新了其中一行的地址。注意,我们在插入数据时使用了参数化查询,这是为了避免SQL注入攻击。
当然,具体的操作和SQL语句需要根据你的具体需求而定。