python

一般在自动化测试中,查询sql会有多行,一般会进行换行处理(python的逻辑单行、物理多行),举例如下:

一般的python语句(行尾加上换行符):

单行:

a = 5

多行:

a = 
5

sql语句(除每行行尾的换行符外,每一行前后都有双引号):

单行:

sql2 = "select version()"

多行:

sql2 = 
    "select " 
    "versi" 
    "on()"

好了,现在我们来看看其中的坑在哪里

假如,你的sql语句中存在注释,如下:

select -- 查询版本号
version()

上面这一句,在sql中可以正常运行,但是,在python中,就会报错,如下:

sql2 = 
 " select -- 查询版本号 " 
 " version() "

cur.execute(sql2)

报错信息:MySQLdb._exceptions.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 '' at line 1")

将sql2打印出来:

select -- 查询版本号  version() 

发现整个sql其实是被当作一个字符串处理的,包括其中的注释,所以会报错,修改如下:

sql2 = 
 " select -- 查询版本号 
" 
 " version() "

加上了一个换行符 ,再次运行,就ok了(注释被当做了真正的注释)

原文地址:https://www.cnblogs.com/xiaochongc/p/14000852.html