Source:
1 ImportPymysql2 3 classMysqlconnect (object):4 #Magic Method, initialization, constructor5 def __init__(self):6Self.db = Pymysql.connect (host='127.0.0.1', user='Root', password='123456', port=3306, database='Xueqiu')7Self.cursor =self.db.cursor ()8 9 def exec(self,sql):Ten Try: One #Execute SQL statement A self.cursor.execute (SQL) - #commit to database execution - Self.db.commit () the except: - #Roll Back when an error occurs - Self.db.rollback () - + defSelect (self,sql): - Try: + self.cursor.execute (SQL) A #get list of all records atResults =Self.cursor.fetchall () - forRowinchResults: - Print(Row) - except: - Print("error:unable to fetch data") - in #Magic Methods, destructors, destructors - def __del__(self): to self.cursor.close () + self.db.close () - the if __name__=='__main__': *MC =Mysqlconnect () $ #mc.exec (' INSERT into news (ID) VALUES (1111111) ')Panax Notoginseng Print(Mc.select ('SELECT * from news;'))
Python Connection MySQL database encapsulation