Python操作mysql数据库出现pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check

下面为python中做mysql数据库插入数据代码操作:

import pymysql.cursors

    # 循环入库操作
    for ll in range(0, len(wallPaperBeanList)):
        # 连接MySQL数据库
        connection = pymysql.connect(host='127.0.0.1', port=3306, user='ad', password='ad', db='AllThingArePower',
                                     charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

        # 通过cursor创建游标
        cursor = connection.cursor()
        insert_sql = "INSERT INTO 'wallpaper' ('category','view_img','img','created_time','img_tag') VALUES ("+ wallPaperBeanList[ll].category +','+wallPaperBeanList[ll].view_img +','+wallPaperBeanList[ll].img +','+wallPaperBeanList[ll].created_time +','+'null' +')'

        # print('category==' + wallPaperBeanList[ll].category + ';view_img==' + str(
        #     wallPaperBeanList[ll].view_img) + ';img==' + str(wallPaperBeanList[ll].img) + ';created_time==' + str(wallPaperBeanList[ll].created_time) + ';img_tag==' + str(wallPaperBeanList[ll].img_tag))
        cursor.execute(insert_sql)

        # 提交SQL
        connection.commit()
        # 关闭数据连接
        connection.close()

运行后就出现了下面这个异常,下面贴下完整的异常日志信息:

pymysql.err.ProgrammingError: (1064, "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 ''wallpaper' ('category','view_img','img','created_time','img_tag') VALUES (Origi' at line 1")

刚开始我一直以为是mysql语法有错误,但找来找去始终没有找到可以改动的地方,百度后网上有博客讲mysql语句拼接的时候里面可能有参数有双引号导致的,使用pymysql.escape_string()方法把有双引号的参数处理一下就行,这个方案没有解决了我的问题,后来找到了一个比较好的解决方案,就是不要用%或者+操作符来拼接SQL语句,应该使用占位符。即execute的第二个参数。关于这个execute()函数的过呢更多详细说明可以参考这两篇博客(https://www.oschina.net/question/1418554_242736和https://stackoverflow.com/questions/775296/python-mysql-parameterized-queries/775399#775399)

修改后的代码:

import pymysql.cursors

    # 循环入库操作
    for ll in range(0, len(wallPaperBeanList)):
        # 连接MySQL数据库
        connection = pymysql.connect(host='127.0.0.1', port=3306, user='ad', password='ad', db='AllThingArePower',
                                     charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

        # 通过cursor创建游标
        cursor = connection.cursor()
                cursor.execute('insert into wallpaper (category,view_img,img,created_time,img_tag) values (%s,%s,%s,%s,%s)', (str(wallPaperBeanList[ll].category), str(
            wallPaperBeanList[ll].view_img),str(wallPaperBeanList[ll].img),str(wallPaperBeanList[ll].created_time),str(wallPaperBeanList[ll].img_tag)))

        # 提交SQL
        connection.commit()
        # 关闭数据连接
        connection.close()

这样运行后就不会出现那个因为sql语句字符串中的特殊字符而报1064的语法异常了。

你可能感兴趣的:(mysql,Python进阶)