Import Pymysql
Class OPMYSQL1: # Classic Class
Pass
Class Opmysql (object): # New Class
def __init__ (self, host, user, password, db, port=3306, charset= ' UTF8 '):
schema = {
' User ': User,
' Host ': Host,
' Password ': password,
' DB ': DB,
' Port ': port,
' CharSet ': CharSet
}
Try
Self.coon = Pymysql.connect (**schema)
Except Exception as E:
Print (' Database connection exception! %s '% e)
Quit ()
Else: # Create a cursor without exception
Self.cur = Self.coon.cursor (cursor=pymysql.cursors.dictcursor)
def execute (Self, SQL):
Try
Self.cur.execute (SQL)
Except Exception as E:
Print (' SQL statement has errors! %s '% e)
Return E
If sql[:6].upper () = = ' SELECT ':
Return Self.cur.fetchall ()
ELSE: # Other SQL statements
Self.coon.commit ()
Return ' OK '
def __del__ (self):
Self.cur.close ()
Self.coon.close ()
YBQ = Opmysql (' 211.149.218.16 ', ' jxz ', ' 123456 ', db= ' Jxz ') # instantiation
Print (Ybq.execute (' select * from Stu; '))
python--Operating Database class