当前位置:   article > 正文

Python中执行 MySQL插入语句报错   :1064, "You have an error in your SQL syntax;_python 报错:"you have an error in your sql syntax; c

python 报错:"you have an error in your sql syntax; check the manual that cor

 

  1. (1064, "You have an error in your SQL syntax;
  2. check the manual that corresponds to your MySQL server version
  3. for the right syntax to use near
  4. 'Darabont,弗兰克·德拉邦特,http://img3.doubanio.com/view/celebrity/s_ratio' at line 1")

SQL语句语法有问题了~

1、有一个方法能帮助我们更快的发现问题,就是输出自己的SQL语句:

输出Python中的MySQL插入语句:

  1. insert_sql = "INSERT INTO db_writers (writer_id, writer_name_en, writer_name, writer_avatars, writer_alt) VALUES ({},{},{},{},{});".format(writer_id, writer_name_en, writer_name, writer_avatars, writer_alt)
  2. print(insert_sql)

运行输出的SQL结果:

  1. INSERT INTO db_writers ( writer_id, writer_name_en, writer_name, writer_avatars, writer_alt )
  2. VALUES
  3.     (
  4.         1047973,
  5.         Frank Darabont,弗兰克·德拉邦特,
  6.     http :// img3.doubanio.com / VIEW / celebrity / s_ratio_celebrity / public / p230.jpg,
  7.     https :// movie.douban.com / celebrity / 1047973 /);

除了writer_id是int类型,其他字段都是varchar类型的,一看问题就明了了,varchar类型的是要用双引号括起来的,是因为我的SQL语句在使用{}的时候,在除了writer_id对应的{}外忘记用 ' ' 包起来了,本来应该用'{}'的。

"INSERT INTO db_writers (writer_id, writer_name_en, writer_name, writer_avatars, writer_alt) VALUES ('{}','{}','{}','{}','{}');".format(writer_id, writer_name_en, writer_name, writer_avatars, writer_alt)
                

这样便不会报错了

同时有时候在字符串内容中有 ' 比如:' Alia s '也会导致报错,这时候如果还要插入到数据库的话需要转义:

比如:

original_title = res['original_title'].replace("\'", "\\\'")

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/508994
推荐阅读
相关标签
  

闽ICP备14008679号