- 帖子
- 3
- 精华
- 0
- 积分
- 11
- 阅读权限
- 10
- 注册时间
- 2019-10-28
- 最后登录
- 2019-10-29
|
A.py文件代码:
import pymysql
# 定义一个类
class MysqlHelper:
# 定义连接数据库的信息函数
def __init__(self, host, port, user, passwd, db, charset):
self.host = host
self.port = port
self.user = user
self.passwd = passwd
self.db = db
self.charset = charset
# 定义一个连接数据库的函数
def connect(self):
self.conn = pymysql.connect(
self.host, self.port, self.user, self.passwd, self.db)
self.cursor = self.conn.cursor()
# 定义一个关闭数据库连接的函数
def close(self):
self.cursor.close()
self.conn.close()
# 定义一个数据库执行的函数
def cud(self, sql, params):
try:
self.connect()
self.cursor.execute(sql, params)
self.conn.commit()
self.close()
print('执行成功!')
except Exception as e:
print('执行出错'+str(e))
# 定义一个数据库查询的函数
def select(self, sql, params):
try:
self.connect()
self.cursor.execute(sql, params)
result = self.cursor.fetchall()
self.close()
print(result)
except Exception as e:
print('执行出错'+str(e))
B.py文件代码:
import pymysql
from MySQLHelper import MysqlHelper
name = input('请输入更正的学生姓名:')
id = int(input('请输入该学生的学籍编号:'))
sql = "UPDATE STUDENTS SET NAME=%s WHERE ID=%s"
sqlhelper = MySQLHelper.MysqlHelper('localhost',3306,'root','Eco0212@@','python3','utf8')
sqlhelper.MysqlHelper.cud(sql, params=[name, id])
运行提示错误:
E:\Python\protects>C:/Users/Administrator/AppData/Local/Programs/Python/Python37-32/python.exe e:/Python/protects/MySQL/mysql_updata.py请输入更正的学生姓名:ww请输入该学生的学籍编号:13Traceback (most recent call last): File "e:/Python/protects/MySQL/mysql_updata.py", line 7, in <module> sqlhelper = MySQLHelper.MysqlHelper('localhost',3306,'root','Eco0212@@','python3','utf8')NameError: name 'MySQLHelper' is not defined
|
|