1

I am running a [Water] Meter Data Management system on Linux and Python 2.7. I have been reading SO posts like this.

What is the proper, safe syntax for constructing a query and not having to use the less safe method involving %s?

rc = test_cur.execute("select m.* from meter m where m.acct_no = '%s' ", acct_no)

I have tried several ways based on the errors I am getting.

Community
  • 1
  • 1
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131

1 Answers1

2

The %s here does not represent a Python string formatting placeholder. In this case, this is a MySQL driver query parameterization placeholder. The placeholder(s) are substituted by the database driver with the parameter(s) passed in a separate argument to execute(). This is different from regular string formatting.

Note that you don't need quotes around the %s in this case - the driver will automatically decide if quotes are needed depending on the parameter type:

rc = test_cur.execute("select m.* from meter m where m.acct_no = %s", (acct_no, ))

Also note the acct_no enclosed in a tuple.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195