PYTHON使用easygui查询Mysql库
刚刚接触PYTHON,做一个有界面的小工具顺便记录一下。
首先把要用到的功能Import一下
import pymysql
import easygui as g
做个IP输入框,并用Print测试一下
msg = "请填写 IP"
title = "设置工具v1.0"
fieldNames = ["*IP"]
fieldValues = []
fieldValues = g.multenterbox(msg, title, fieldNames)
while True:
if fieldValues == None:
break
errmsg = ""
for i in range(len(fieldNames)):
option = fieldNames[i].strip()
if fieldValues[i].strip() == "" and option[0] == "*":
errmsg += ("有漏填的" % fieldNames[i])
if errmsg == "":
break
fieldValues = g.multenterbox(errmsg, title, fieldNames, fieldValues)
SIP = fieldValues[0]
print("您填写的IP:%s" % str(SIP))
连接MYSQL数据库
可以执行多条,以下记录sql1 的查询,并print测试
try:
# 获取数据库连接
conn = pymysql.connect(host=SIP, user='user', passwd='psssword', db='dbname', port=3306, charset='utf8')
# 打印数据库连接对象
print('数据库已连接')
# 获取游标
cur = conn.cursor()
print("游标是:" + str(cur))
# 查询sql语句
sql1 = "select logic_id,tpm_print_logic.printer_id,tpm_printter_info.port_num from tpm_print_logic LEFT JOIN tpm_printter_info ON tpm_print_logic.printer_id = tpm_printter_info.printer_id limit 10"
try:
# 执行SQL语句
cur.execute(sql1)
# 向数据库提交
conn.commit()
result1 = cur.fetchall()
except:
# 发生错误时回滚
conn.rollback()
print("查询结果1:" + str(result1))
cur.close()
conn.close()
except Exception as e:
print(e)
查询结果输出到 msgbox()
查询结果1:((3, ‘EPSON4’, 4), (4, ‘EPSON4’, 4), (7, ‘EPSON6’, 9), (8, ‘EPSON4’, 4), (16, ‘EPSON1’, 7), (17, ‘EPSON4’, 4), (18, ‘EPSON1’, 7), (22, ‘EPSON3’, 2), (26, ‘EPSON5’, 10), (27, ‘EPSON5’, 10))
整理并按顺序去除数组中的查询结果,输出到msgbox()
a=''
for i in result1:
print(i[0],i[1],i[2])
a = a + str(i[0]) + '\t' + str(i[1]) + '\t' + str(i[2]) + '\n'
g.msgbox("查询结果:\n逻辑号\t打印机\t串口号 \n" + a,ok_button="OK")
输出内容怎么居中? 还要研究一下,先记录到这里。