欢迎大家加入京东淘宝捡垃圾群: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, '条数据')
如需转载,请附上链接信息。