pymysql 查找指定IP,修改两列数据
时间: 2023-12-03 15:34:36 浏览: 40
以下是使用pymysql查找指定IP并修改两列数据的示例代码:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='password', database='test')
cursor = conn.cursor()
# 查找指定IP的记录
ip = '192.168.1.100'
sql = "SELECT * FROM mytable WHERE ip_address = %s"
cursor.execute(sql, ip)
result = cursor.fetchone()
if result:
# 修改两列数据
new_status = 'blocked'
new_reason = 'suspected attack'
sql = "UPDATE mytable SET status = %s, reason = %s WHERE ip_address = %s"
cursor.execute(sql, (new_status, new_reason, ip))
conn.commit()
print("Data updated successfully.")
else:
print("No record found for the specified IP address.")
# 关闭连接
cursor.close()
conn.close()
```
在上面的示例中,我们首先连接到数据库,然后使用pymysql执行SQL查询以查找指定IP地址的记录。如果找到了记录,则使用UPDATE语句修改status和reason列的值,并使用commit()方法提交更改。最后,我们关闭连接。