Created
November 8, 2018 01:40
-
-
Save ayuLiao/00c547764e9e8596ba300d2108a858a7 to your computer and use it in GitHub Desktop.
python执行sql,当遇到该sql语句报错没有该表时自己创表 适用于表结构相同单纯表名不同的系统
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@debug | |
def sql2(self, sql): | |
def execsql2(db_con,cur,sql): | |
''' | |
if you first close the conn then use ping or any other operating, you | |
will get error about : err.InterfaceError("(0, '')"). | |
so , do any operate before the close operating | |
''' | |
#reconnect MySQL | |
db_con.ping(reconnect=True) | |
cur.execute(sql) | |
# commit --> MySQL will change | |
res = db_con.commit() | |
cur.close() | |
return res | |
cur = self.db_con.cursor() | |
try: | |
return execsql2(self.db_con, cur, sql) | |
except Exception,e: | |
# if table doesn't exit , create table | |
if len(e.args) >=2: | |
errdata = e.args[1] | |
# Table '9377game.newtable' doesn't exist | |
errtable = re.findall(errpattern, errdata)[0] if re.findall(errpattern, errdata) else 0 | |
if errtable: | |
errtable = errtable.split('.')[1] | |
self.createTable(errtable,createsql%errtable) | |
# insert data again | |
return execsql2(self.db_con, cur, sql) | |
raise # pass up the error | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment