Content

python-pymysql如何实现更新mysql表中任意字段数据(python 判断语法)这样也行?

文章摘要

这篇文章介绍了名为`Changehous`的自定义Python函数,用于修改MySQL数据库中的字段数据。函数的主要功能包括: 1. 连接到MySQL数据库,通过输入连接信息(主机、用户名、密码、端口、数据库名)实现动态连接。 2. 通过用户输入指定要修改的字段名、修改内容和要更新的ID,根据输入的字段名自动生成对应的`MySQL UPDATE`语句。 3. 提供了详细的条件判断机制,能够根据输入的字段名(如'residential'、'house'、'area'等)自动生成并执行相应的更新操作。 4. 包含异常处理逻辑,确保在操作过程中出现问题时能够及时提示并终止程序。 5. 最后执行提交操作后,会关闭数据库连接和游标,释放资源。 该函数通过输入和条件判断实现了对MySQL数据库字段的灵活修改,具有较高的实用性和灵活性。

def Changehous(): “”” 修改mysql里的任意字段数据 “”” host=”localhost”#默认为localhost user=”root”#用户名 passwd=”000000″#此处输入连接mysql的密码 port=”3306″#端口号可以不输入 database=”hous”#需要连接的数据库名(不是表名) db=pymysql.connect(host, user, passwd, database)#连接mysql cursor=db.cursor()#创建游标 #定义一个列表,来来装自己的字段名 #若字段名过多的话不建议使用这种方法 title=[‘residential’,’house’,’area’,’orientation’,’floor’,’years’,’totalprice’] field=str(input(“请输入要修改的字段名:”))#控制台输入 if field in title: #如果输入的字段名在title里面,那么就可以进行查询了. name=str(input(“请输入要修改的内容”)) id=int(input(“请修改要更新内容的id:”)) if field==title[0]: sql=”update mashine set residential='{}’ where id='{}'”.format(name,id) elif field==title[1]: sql=”update mashine set house='{}’ where id='{}'”.format(name, id) elif field==title[2]: sql=”update mashine set area='{}’ where id='{}'”.format(name, id) elif field==title[3]: sql=”update mashine set orientation='{}’ where id='{}'”.format(name, id) elif field==title[4]: sql=”update mashine set floor='{}’ where id='{}'”.format(name, id) elif field==title[5]: sql=”update mashine set years='{}’ where id='{}'”.format(name, id) elif field==title[6]: sql=”update mashine set totalprice='{}’ where id='{}'”.format(name, id) else: print(“输入有误,没有查询到该字段!”) try: cursor.execute(sql) db.commit()#提交给数据库 print(“修改成功”) except Exception as e: print(“修改失败”) finally: db.close()#关闭数据库 cursor.close()#关闭游标