1. Adding and deleting to seal the mysqlhelper.py
1 ImportPymysql as PS2 3 classMysqlhelper:4 def __init__(self, host, user, password, database, CharSet):5Self.host =Host6Self.user =User7Self.password =Password8Self.database =Database9Self.charset =CharSetTenSelf.db =None OneSelf.curs =None A #Database Connection - defOpen (self): -Self.db = Ps.connect (Host=self.host, User=self.user, Password=self.password,database=self.database, charset=self.charset) theSelf.curs =self.db.cursor () - #Database Shutdown - defClose (self): - self.curs.close () + self.db.close () - #Data deletion and modification + defcud (self, SQL, params): A Self.open () at Try: - self.curs.execute (SQL, params) - Self.db.commit () - Print("OK") - except : - Print('cud error occurred') in Self.db.rollback () - self.close () to #data Query + deffind (self, SQL, params): - Self.open () the Try: *result =self.curs.execute (SQL, params) $ self.close ()Panax Notoginseng Print("OK") - returnresult the except: + Print('Find error occurred')
2. Data query (Introduce encapsulation Class)
1 fromMysqlhelperImportMysqlhelper2 3MH = Mysqlhelper ('localhost','Root','123456','Test','UTF8')4sql ="SELECT * from user where name=%s"5 Print(Mh.find (SQL,'Xiao Ming'))
3. Data modification (introduction of package Class)
1 fromMysqlhelperImportMysqlhelper2 3MH = Mysqlhelper ('localhost','Root','123456','Test','UTF8')4sql ="INSERT INTO User (Name,password) VALUES (%s,%s)"5Mh.cud (SQL, ('Small Light','123456'))
Python MySQL learning-simple additions and deletions to the seizure pack