python与MySQL交互

from pymysql import connect

class MysqlHelp:

def init(self,database,host=’localhost’,user=’root’,password=’123456’,charset=’utf8’,port=3306):

self.port=port

self.charset=charset

self.user=user

self.host=host

self.password=password

self.database=database

def open(self):

self.conn=connect(host=self.host,user=self.user,password=self.password,charset=self.charset,port=self.port,database=self.database)

self.cur= self.conn.cursor()

def close(self):

self.conn.close()

self.cur.close()

def workon(self,sql,l=[]):

self.open()

try:

self.cur.execute(sql,l)

self.conn.commit()

except Exception as e:

self.conn.rollback()

print(e)

self.close()

def getall(self,sql,l=[]):

self.open()

try:

self.cur.execute(sql,l)

print(‘ok’)

data=self.cur.fetchall()

except Exception as e:

self.conn.rollback()

print(e)

self.close()

return data

if name==’main‘:

mysql = MysqlHelp(‘MOSHOU’)

sql=”select * from city”

print(mysql.getall(sql))

你可能感兴趣的:(python基础,python)