建立连接数据库的类,命名为mysql_class.py
from pymysql import *
class Mysqlpython:
def __init__(self, host, port, db, user, passwd, charset="utf8"):
self.host = host
self.port = port
self.db = db
self.user = user
self.passwd = passwd
self.charset = charset
def open(self):
self.conn = connect(host=self.host, port=self.port, db=self.db,
user=self.user, passwd=self.passwd,
charset=self.charset)
self.cursor = self.conn.cursor()
def close(self):
self.cursor.close()
self.conn.close()
def zhixing(self, sql):
self.open()
self.cursor.execute(sql)
self.conn.commit()
self.close()
print("OK")
创建实例对象sqlh,传入实参,执行sqlh实例对象下的zhixing函数
from mysql_class import Mysqlpython
sqlh = Mysqlpython("localhost", 3306, "city", "root", "123456")
sql_update = "update sheng set id=150 where id=3;"
sqlh.zhixing(sql_update)