Python操作MySQL数据表及表中数据
实现功能:
1.不存在’wztd’表便新建表,否则操作表数据;
2.如果存在cityid为’100’的数据便更新,不存在便插入数据;
import pymysql
def tomysql():
TableName = 'wztd'
dic = {'cityid':'1000', 'tdate':'2020-11-23', 'tweek': '星期二', 'city': '河北', 'wea': '小雨', 'tem2': '-1', 'win': '东风','win_speed': '1级'}
try:
# 连接数据库
db = pymysql.connect(host='localhost', user='root', passwd='root', db='mydb') # 链接数据库
# 建立游标
cur = db.cursor()
COLstr = '' # 列的字段
ROWstr = '' # 行字段
ColumnStyle = ' VARCHAR(20)'
COL = '' # 列的字段2,不带varchar,插入数据时使用
# 数据库表头需用字段
for key in dic.keys():
COL = COL + key + ','
if ('id' in key):
COLstr = COLstr + key + ColumnStyle + ' NOT NULL ' + ','
else:
COLstr = COLstr + key + ColumnStyle + ','
# 数据库的值
for value in dic.values():
if value != None:
ROWstr = ROWstr + "'" + value + "'" + ','
else:
ROWstr = ROWstr + 'null' + ','
# 去掉最后一个逗号
COLstr = COLstr[:-1]
ROWstr = ROWstr[:-1]
COL = COL[:-1]
# 推断表是否存在,存在运行try。不存在运行except新建表,再insert
try:
# 创建表
cur.execute("CREATE TABLE IF NOT EXISTS %s (%s)" % (TableName, COLstr))
# 更新表的字段属性
# cur.execute("ALTER TABLE %s CHANGE COLUMN cityid cityid INT NOT NULL PRIMARY KEY" % TableName)
except Exception as e:
# 打印异常
print('建表错误:',e)
db.rollback() # 回滚错误
# 如果数据存在便更数据,如果数据不存在便插入数据
try:
c_id = ROWstr[1:10]
cur.execute("SELECT * FROM %s WHERE cityid='%s'" % (TableName, c_id))
reslut = cur.fetchall()
if reslut:
print('已存在的数据更新')
tdt = dic.get('tdate')
wk = dic.get('tweek')
ct = dic.get('city')
wa = dic.get('wea')
t2 = dic.get('tem2')
wn = dic.get('win')
ws = dic.get('win_speed')
cur.execute("UPDATE %s SET tdate='%s',tweek='%s',city='%s',wea='%s',tem2='%s',win='%s',win_speed='%s'/
WHERE cityid='%s'" % (TableName, tdt, wk, ct, wa, t2, wn, ws, c_id))
else:
print('不存在的数据插入')
cur.execute("INSERT INTO %s (%s) /n VALUES (%s)" % (TableName, COL, ROWstr))
except Exception as e:
print('数据插入错误:%s' % e)
db.rollback() # 回滚错误
# 提交
db.commit()
cur.close()
db.close()
except Exception as e:
print('数据错误:',e)
tomysql()
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/17725.html