python操作MySQL資料表及表中資料

2021-10-10 19:07:50 字數 2323 閱讀 9308

實現功能:

1.不存在'wztd'表便新建表,否則操作表資料;

2.如果存在cityid為'100'的資料便更新,不存在便插入資料;

import pymysql

def tomysql():

tablename = 'wztd'

dic =

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()

參考文章:

python操作mysql查詢資料

首先需要連線資料庫,然後才查詢出資料。例如下表名字為 sinauser iduse id use name11 db12 2db233 db3class database def init self self.conn mysqldb.connect 連線資料庫 host 連線你要取出資料庫的ip,...

python操作MySQL資料庫

堅持每天學一點,每天積累一點點,作為自己每天的業餘收穫,這個文章是我在吃飯的期間寫的,利用自己零散的時間學了一下python操作mysql,所以整理一下。我採用的是mysqldb操作的mysql資料庫。先來乙個簡單的例子吧 import mysqldb try conn mysqldb.connec...

Python操作Mysql資料庫

coding utf8 author yangjing import mysqldb 查詢。def select host user root password port 3306,db sql connect mysqldb.connect host host,user user,passwd p...