Cursor.execute () Operations database Write SQL statements here
Commit () writes to the database
Cursor.close () Close this operation, or terminate it.
Self.conn.close () Close the connection database, Conn is the custom method, see below
classDB ():def __init__(self):#Self . Db_host = Db_host#Self . Db_port = Db_port#Self . Db_user = Db_user#Self . Db_pwd = Db_pwd#Self . Db_name = db_nameSelf.conn=self.getconnection ()defgetconnection (self):returnMySQLdb.connect (Host='127.0.0.1',#set MySQL addressport=3306,#set the port numberUser='Root',#Set user name passwd='Root',#Set Password DB='MyDB',#Database namecharset='UTF8' #Set Encoding )defquery (self, sqlString): Cursor=self.conn.cursor () cursor.execute (sqlString) returndata=Cursor.fetchall () cursor.close () Self.conn.close ( )returnReturndatadefUpdate (self, sqlString): Cursor=self.conn.cursor () cursor.execute (sqlString) self.conn.commit () Cursor.close () self.conn.close ()if __name__=="__main__": DB=DB ()PrintDb.query ("show tables;")
You can add a common method yourself
Python operation MySQL Database common methods