1

I am using SQL server and need to run the following SQL via Python script

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

angus
  • 3,210
  • 10
  • 41
  • 71

2 Answers2

2

'.' is the string ., you want "'.'", the string '.'

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

As @Justin Ezequiel's answer notes, do beware of SQL injections here!

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. 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.

ti7
  • 16,375
  • 6
  • 40
  • 68
2

Use parameters to avoid SQL-injection attacks.

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

cursor = conn.cursor()
cursor.execute(sql, params)
  • 1
    This has a very valuable point about injection and provides a good solution to it, but doesn't really give weight to how dangerous the problem is! – ti7 Feb 24 '21 at 19:36