简体   繁体   English

通过 python 脚本的 SQL 的语法(',' 附近的语法不正确)

[英]Syntax for SQL via python script (Incorrect syntax near ',')

I am using SQL server and need to run the following SQL via Python script我正在使用 SQL 服务器,需要通过 Python 脚本运行以下 SQL

SELECT DISTINCT LEN(Wav)-CHARINDEX('.', Wav) FROM <>;

I have tried to play with the String but couldn't figure out how to work around the dot character.我曾尝试使用字符串,但无法弄清楚如何解决点字符。

sql = 'SELECT DISTINCT LEN(Wav)-CHARINDEX({}, Wav) FROM xxx'.format('.')
print(sql)

cursor = conn.cursor()
cursor.execute(sql)

Any idea how to resolve this知道如何解决这个问题

Thank you谢谢

'.' is the string .是字符串. , you want "'.'" , the string '.' , 你想要"'.'" , 字符串'.'

>>> print("{}".format('.'))
.
>>> print("{}".format("'.'"))
'.'

As @Justin Ezequiel 's answer notes, do beware of SQL injections here!正如@Justin Ezequiel的回答,请注意此处的 SQL 注射!

Specifically, unfiltered user inputs can and will cause an SQL injection where unanticipated commands can be run against the target database by breaking out of the raw string.具体来说,未经过滤的用户输入可以并且将导致 SQL 注入,其中可以通过中断原始字符串对目标数据库运行意外命令。 These can do anything your connection has permission to do, such as retrieving, modifying, or deleting arbitrary data .这些可以执行您的连接有权执行的任何操作,例如检索、修改或删除任意数据

A traditional approach is to use prepared statements传统的方法是使用准备好的语句

In Python, you can also use a regex or other test to explicitly error for statements with control characters ( if not re.match(r"^[a-zA-Z\d _+-]+$"), s):raise_ ) or use (trust) an escaping library to do it for you if you must take arbitrary strings.在 Python 中,您还可以使用正则表达式或其他测试来显式错误地检测带有控制字符的语句( if not re.match(r"^[a-zA-Z\d _+-]+$"), s):raise_ )或使用(信任)一个 escaping 库来为你做这件事,如果你必须采取任意字符串。

Use parameters to avoid SQL-injection attacks .使用参数来避免SQL 注入攻击

sql = 'SELECT DISTINCT LEN(Wav)-CHARINDEX(?, Wav) FROM xxx' # note placeholder (?)
print(sql)
params = ('.',) # tuple

cursor = conn.cursor()
cursor.execute(sql, params)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM