import pymysql import configMysql as c #Configuration file, write your own import re class ConDb(): def openClose( fun ): def run(self,sql= None ): #Create database connection db=pymysql.connect( host =c.host , port =c.port , user =c.user, password =c.pwd, db =c.db, charset =c.charset) #Create cursor cursor = db.cursor() try : #Use decorator, fun is Arguments for the decorator. . . run sql statement cursor.execute(fun(self,sql)) #get the return value li=cursor.fetchall() #commit the transaction db.commit() except Exception as e: #if an error occurs, roll back the transaction db.rollback() #print Error message print ( 'Running' , str (fun), 'An error occurred during the method, error code: ' ,e) finally : #Close the cursor and database connection cursor.close() db.close() try : #Return sql execution information return list (li) except : print ( 'No return value, please check the code, the information appears in the decorator method in the ConDb class' ) return run #runSql is not encapsulated, you can run sql directly @openClose def runSql( self ,sql): #Call this method to execute sql print ( 'for debugging, display sql:' ,sql) return sql #Switch database def tab( self ,db ): sql= 'use {}' .format(db) self .runSql(sql) #Create database def create_DB( self ,name): sql= '''CREATE DATABASE {} ''' .format(name) self .runSql(sql) #Create table def create_TB( self ,dbname= '' ,tbname= '' ,enging= "InnoDB" ,charset= " utf8" ,**kwargs): ''' :param dbname: database name :param tbname: table name :param enging: data engine :param charset: default encoding :param kwargs: new columns and indexes :return : PRIMARY=" KEY('id')" Set the primary key index id and replace it with the column to be set as the primary key UNIQUE = " KEY `name` (`name`)" Set the context index, name can be replaced ''' ''' 使用案例: import conMySql con=conMySql.ConDb() con.create_TB('test','student1',id="int(10)",name="varchar(255)",PRIMARY="KEY('id')" ,UNIQUE = "KEY `name` (`name`)" ) ''' self.runSql('''use {}'''.format(dbname)) li = [] for k, v in kwargs.items(): li.append( '{} {}' .format(k, v)) sql = ''' CREATE TABLE `{}` ( "{}" ) ENGINE={} DEFAULT CHARSET={} '''.format(tbname, li, enging, charset) sql = re.sub( r"""\'|\"|\[|\]""" , '' , sql) self .runSql(sql) #Insert data def insert_TB( self ,tableName,items,*args ): ''' :param tableName: inserted table name :param items: data source, a non-nested list :param args: specified column, do not fill in and do not specify :return : ''' ''' Use case: import conMySql con=conMySql.ConDb() does not specify the insert column con.insert_TB('tableName', data source) inserts the specified column con.insert_TB('tableName' , data source, 'column name 1', 'column name 2') ''' args=str(args) args=re.sub("'",'',args) items=re.sub(r"\[|\]",'',str(items)) if items: sql=''' INSERT INTO {} {} VALUES ({}) '''.format(tableName,args,items) else: sql = ''' INSERT INTO {} VALUES ({}) '''.format(tableName, items) self.runSql(sql)
package pymysql,
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325800917&siteId=291194637
Recommended
Ranking