Python Pig Herd Management: Troubleshooting 'self.cursor.execute(sql)' Error in MySQL Database Interaction
"代码中self.cursor.execute(sql)出错的原因是因为在使用pymysql库时,execute()函数只接受一个参数,即SQL语句。而在代码中,使用了f-string将SQL语句中的字符串变量进行了格式化,导致execute()函数无法正确解析SQL语句。\n\n要解决这个问题,可以将SQL语句和变量分开,分别传递给execute()函数。具体修改如下:\n\n1. 将SQL语句中的变量替换为占位符"?"。\n2. 将变量作为参数传递给execute()函数。\n\n修改后的代码如下:\n\npython\ndef select(self):\n db = pymysql.connect(host='localhost', user='root', password='111111', port=3306, db='student', charset='utf8')\n self.cursor = db.cursor()\n sql = "SELECT * FROM pigherd WHERE herdid=%s OR herdname=%s OR creattime=%s"\n self.cursor.execute(sql, (self.herdid_t.get(), self.herdname_t.get(), self.creattime_t.get()))\n result = self.cursor.fetchone()\n self.result_label.config(text=result)\n db.close()\n
\n\n这样修改后,execute()函数会正确解析SQL语句,并将变量传递给占位符,从而避免了报错。\n
原文地址: http://www.cveoy.top/t/topic/pNCY 著作权归作者所有。请勿转载和采集!