1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 #__author__ = "Blzhu"4 """5 Python study6 date:20177 """8 #-*-coding:utf-8-*-9 __author__='djstava@gmail.com'Ten One ImportLogging A ImportPymysql - - the classMysqlcommand (object): - def __init__(self, host, port, user, passwd, DB, Table, CharSet): -Self.host =Host -Self.port =Port +Self.user =User -Self.password =passwd +Self.db =DB ASelf.table =Table atSelf.charset =CharSet - - defConnectmysql (self): - Try: -Self.conn = Pymysql.connect (Host=self.host, Port=self.port, User=self.user, passwd=Self.password, -Db=self.db, charset=self.charset) inSelf.cursor =self.conn.cursor () - Print('Connect'+ self.table +'correctly!') to except: + Print('connect MySQL error.') - the defQuerymysql (self): *sql ="SELECT * from"+self.table $ Panax Notoginseng Try: - Print("Query Mysql:") the self.cursor.execute (SQL) + #row = Self.cursor.fetchone () A forDinchSelf.cursor: the Print(Str (d[0]), str (d[1]), str (d[2])) + #print (Row) - $ except: $ Print(SQL +'execute failed.') - - defInsertmysql (self, id, name, sex): thesql ="INSERT into"+ self.table +"VALUES ("+ ID +","+"'"+ name +"',"+"'"+ Sex +"')" - Try:Wuyi Print("Insert Mysql:") the self.cursor.execute (SQL) - Print(SQL) Wu except: - Print("insert failed.") About $ defupdatemysqlsn (self, Name, sex): -sql ="UPDATE"+ self.table +"SET sex= '"+ Sex +"'"+"WHERE name= '"+ name +"'" - Print("Update SN:"+sql) - A Try: + self.cursor.execute (SQL) the Self.conn.commit () - except: $ Self.conn.rollback () the the defDeletemysql (self, id):#Delete thesql ="DELETE from%s WHERE id= '%s '"%(Self.table,id) the #"Delete from student where zid= '%s '"% (ID) - Try: in self.cursor.execute (SQL) the Print(SQL) the Self.conn.commit () About Print("Delete the"+ ID +"th row successfully!") the except: the Print("Delete failed!") the Self.conn.rollback () + - defClosemysql (self): theSelf.conn.commit ()#does not execute this sentence, the action is not written to the databaseBayi self.cursor.close () the self.conn.close () the - - if __name__=='__main__': theZblmysql = Mysqlcommand (host='localhost', user='Root', passwd='Root', db='Zbltest1', port=3306, table='Student2', thecharset='UTF8') the Zblmysql.connectmysql () the Zblmysql.querymysql () -Zblmysql.insertmysql ('5','ZBL5','Mans') the Zblmysql.querymysql () theZblmysql.deletemysql (id=2) the Zblmysql.querymysql ()94ZBLMYSQL.UPDATEMYSQLSN (name='ZBL5', sex='woman') the Zblmysql.querymysql () theZblmysql.closemysql ()
Reference:
It's fun!