ayuLiao
11/8/2018 - 1:40 AM

python执行sql,自动创表

python执行sql,当遇到该sql语句报错没有该表时自己创表

适用于表结构相同单纯表名不同的系统

@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