python-pymysql实现更新mysql表中任意字段数据

更新MySQL随意字段里的数据

下面是我的mysql所有字段名
若字段名太多不建议使用以下方法

在这里插入图片描述

这里sql语句要注意一下双引号里面用单引号.

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()#关闭游标

这里可以看到我的表中数据

在这里插入图片描述

现在我们运行程序来修改某一字段
想改那个字段就输入那个字段名,这里用我的residential字段做个示范

在这里插入图片描述

原内容为:大道1号,现在我将它修改为:小道二号,我的主键id为1205

在这里插入图片描述
在这里插入图片描述

以上就是更新任意字段数据的代码,有需要的可以复制

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值