python 数据库 插入及修改数据

欢迎大家加入京东淘宝捡垃圾群:698433653  

这里以我自己的一个项目进行实例:要更新数据 就要判断数据是否存在 ,一个if条件判断引用其中,

def output():

  
    global sfname
    if sfname != '':
        dcm = pydicom.read_file(sfname)
        # 打开数据库连接
        connect = pymysql.Connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='root',
            db='db1',
            charset='utf8'
        )
        # 使用cursor()方法获取操作游标 
        cursor = connect.cursor()
        
        #判断插入还是更新
        selectsql = "SELECT count(PatientID) PatientID FROM br where PatientID = %d"
        selectdata = (int(dcm.PatientID))
        cursor.execute(selectsql % selectdata)
        selectresult = cursor.fetchall() #将返回所有结果
        selectresult = selectresult[0]
        selectresult = selectresult[0]
        print(selectresult)
        if selectresult == 0:    
            sql = "INSERT INTO br (Filename, PatientID, PatientAge,Width,Height,BitDepth,InstitutionName,Comment) VALUES ( '%s',  %d, %d , %d, %d, %d, '%s', '%s')" #前者是key   后者是values
            data = (sfname.split('/')[-1], int(dcm.PatientID), int(dcm.PatientAge[:-1]), int(dcm.pixel_array.shape[0]), int(dcm.pixel_array.shape[1]), int(dcm.BitsAllocated), dcm.InstitutionName, zhuyi1)
            # 执行SQL语句
            cursor.execute(sql % data)#data的值添加至sql
            # 提交修改
            connect.commit()
            print('成功插入', cursor.rowcount, '条数据')
        else:
            sql = "update br set Comment = '%s' where PatientID = %d"
            data = (zhuyi1 , int(dcm.PatientID))
            cursor.execute(sql % data)
            connect.commit();
            print('成功修改', cursor.rowcount, '条数据')

如需转载,请附上链接信息。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值