下面是我给他们起的名字。
现在修改完名字之后,导出成MainWindow.ui文件
打开anaconda的shell
现在就产生了MainWindow.py,打开它
打开pycharm,创建一个新的名为askForLeave的project,把MainWindow.py移进来。
创建Leave.py作为主程序(起名废)
现在给MainWindow.py配置环境
写的代码如下
def ask4leave(self):
logmsg=''
strSN=self.lineEdit_studentNumber.text()
strCN=self.lineEdit_classNumber.text()
strW=self.lineEdit_week.text()
intW=int(strW)
strO=self.lineEdit_order.text()
intO=int(strO)
strR=self.lineEdit_reason.text()
print('Connecting to MSSQL...')
cnxn = pyodbc.connect(
'DRIVER={SQL Server};SERVER=localhost;DATABASE=register;UID=sa;PWD=gslsgsls')
print('Connected...')
cursor = cnxn.cursor()
sql = "insert into 请假(学号,课程号,周次,编号,请假理由,处理状态) values("+strSN+","+strCN+","+intW+","+\
intO+","+strR+",'未处理')"
logmsg=sql
try:
cursor.execute(sql)
cnxn.commit()
cnxn.close()
print("提交成功!")
logmsg += "\n已提交!"
self.lineEdit_studentNumber.clear()
self.lineEdit_classNumber.clear()
self.lineEdit_week.clear()
self.lineEdit_order.clear()
self.lineEdit_reason.clear()
flag=1
except:
if flag==0:
print("提交失败")
logmsg += '提交失败'
现在尝试运行一下:
建立了一些脚手架
print('Connected...')
cursor = cnxn.cursor()
print("成功创建游标")
print(strSN,strCN,intW,intO,strR)
sql = "insert into registration values('" + strSN + "', '" + strCN + "', '" + intW + "', '" + intO + "', '" +strR+ "')"
print('成功定义sql语句')
logmsg=sql
flag=0
try:
print("开始尝试")
所以问题出在赋值语句sql = "insert into registration values('" + strSN + "', '" + strCN + "', '" + intW + "', '" + intO + "', '" +strR+ "')"
原来问题出在python语句中int类型变量不能和字符串直接相加。
改成
sql = "insert into 请假(学号,课程号,周次,编号,请假理由,处理状态) values("+strSN+","+strCN+","+strW+","+strO+\
","+strR+",'未处理')"
现在的结果是这样的:
最后发现报错的原因还是这句sql的赋值语句,单引号忘记了,还有有些逗号是中文格式的。又修改了一下:
sql = "insert into 请假(学号,课程号,周次,编号,请假理由,处理状态)values("+"'"+strSN+"'"+","+"'"+strCN+"'"+","\
+strW+","+strO+","+"'"+strR+"'"+",'未处理')"
就成功了!!
所以以下是代码:
def ask4leave(self):
logmsg=''
strSN=self.lineEdit_studentNumber.text()
strCN=self.lineEdit_classNumber.text()
strW=self.lineEdit_week.text()
intW=int(strW)
strO=self.lineEdit_order.text()
intO=int(strO)
strR=self.lineEdit_reason.text()
print('Connecting to MSSQL...')
cnxn = pyodbc.connect(
'DRIVER={SQL Server};SERVER=localhost;DATABASE=register;UID=sa;PWD=gslsgsls')
print('Connected...')
cursor = cnxn.cursor()
sql = "insert into 请假(学号,课程号,周次,编号,请假理由,处理状态)values("+"'"+strSN+"'"+","+"'"+strCN+"'"+","\
+strW+","+strO+","+"'"+strR+"'"+",'未处理')"
print(sql)
logmsg=sql
flag=0
try:
cursor.execute(sql)
cnxn.commit()
cnxn.close()
print("提交成功!")
logmsg += "\n已提交!"
flag=1
self.lineEdit_studentNumber.clear()
self.lineEdit_classNumber.clear()
self.lineEdit_week.clear()
self.lineEdit_order.clear()
self.lineEdit_reason.clear()
except:
if flag==0:
print("提交失败")
logmsg += '提交失败'
别忘了在setupUi里加一句:
self.pushButton.clicked.connect(self.ask4leave)