老师代码写的有什么问题么,和老师返回的结果不一样

老师代码写的有什么问题么,和老师返回的结果不一样

from db.mysql_db import pool

class NewsDao:
   def seratch_unreview_list(self,page):
       try:
           con = pool.get_connection()
           cursor = con.cursor()
           sql = "SELECT n.id,n.title,t.type,u.username" \
                 "FROM t_news n JOIN t_type t ON n.type=t.id" \
                 "WHERE n.state=%s" \
                 "ORDER BY n.create_time DESC" \
                 "LIMIT %s,%s"
           cursor.execute(sql,("待审批",(page-1)*10,10))
           result = cursor.fetchall()
           return result
       except Exception as e:
           print(e)
       finally:
           if "con" in dir():
               con.close()

service = NewsDao()
rest = service.seratch_unreview_list(1)
print(rest)

运行结果;

D:\untitled1\vega\venv\Scripts\python.exe D:/untitled1/vega/db/news_dao.py

1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'n JOIN t_type t ON n.type=t.idWHERE n.state='待审批'ORDER BY n.create_time DE' at line 1

None


Process finished with exit code 0


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
为学习而奋斗 2020-07-06 13:56:48

同学,您好:
同学检查一下下面这个SQL语句
sql = "SELECT n.id,n.title,t.type,u.username" \
"FROM t_news n JOIN t_type t ONn.type=t.id"\
"WHERE n.state=%s" \
"ORDER BY n.create_time DESC" \
"LIMIT %s,%s"
同学发现了没有,老师的SQL语句每一个关键字都是有加空格的,例如在from前面需要加个空格,否则就是u.usernamefrom,那这样子的话,会导致SQL关键字和普通的字段黏在了一起,所以会报错,所以同学需要在每一个关键字前面加一个空格,像from,where,order by,还有limit前面需要加个空格才行。
如果我的回答解决了同学的疑惑,请采纳!祝学习愉快~

  • 提问者 Buck_messic #1
    根据老师的知道修改了代码: from db.mysql_db import pool class NewsDao: def seratch_unreview_list(self,page): try: con = pool.get_connection() cursor = con.cursor() sql = "SELECT n.id,n.title,t.type,u.username " \ " FROM t_news n JOIN t_type t ON n.type=t.id " \ " WHERE n.state=%s " \ " ORDER BY n.create_time DESC " \ " LIMIT %s,%s" cursor.execute(sql,("待审批",(page-1)*10,10)) result = cursor.fetchall() return result except Exception as e: print(e) finally: if "con" in dir(): con.close() service = NewsDao() rest = service.seratch_unreview_list(1) print(rest) 运行结果还是:D:\untitled1\vega\venv\Scripts\python.exe D:/untitled1/vega/db/news_dao.py 1054 (42S22): Unknown column 'u.username' in 'field list' None Process finished with exit code 0
    2020-07-06 14:22:47
  • 好帮手慕笑蓉 回复 提问者 Buck_messic #2
    同学,你好。sql语句少些了一部分内容,导致u.username找不到,可更改为: sql = "SELECT n.id,n.title,t.type,u.username " \ "FROM t_news n JOIN t_type t ON n.type_id=t.id " \ "JOIN t_user u ON n.editor_id=u.id " \ "WHERE n.state=%s " \ "ORDER BY n.create_time DESC " \ "LIMIT %s,%s" 如果解决了你的疑惑,请采纳,祝学习愉快~
    2020-07-06 15:19:17
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师