Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does pyodbc support any form of named parameters?

I know sqlite3 has

data = {'test_col': 012345679}
sqlite3_conn.execute("""
    UPDATE test_db SET test_col = :test_col
    ;""", data)

and mysql-connector-python has

data = {'test_col': 012345679}
mysql_conn.execute("""
    UPDATE test_db SET test_col = %(test_col)s
    ;""", data)

but does pyodbc support any form of named parameters? I like being able to just pass a dict to the execute method. It is very convenient, and with some of my queries, such as INSERT INTO ... ON DUPLICATE KEY UPDATE, it is needed.

like image 286
randomdev2 Avatar asked Sep 23 '15 20:09

randomdev2


People also ask

Does Pyodbc support named parameters?

The problem that you will encounter when parameterizing a query with an ORDER BY clause is that pyodbc supports parameters for column values but not column names. So, you are not able to pass column names dynamically.

What does Pyodbc connect return?

Returns a new Cursor Object using the connection. pyodbc supports multiple cursors per connection but your database may not.

What is the use of Pyodbc?

The pyodbc module allows connecting to data sources from Python on Windows, macOS, and Linux, for both 32-bit and 64-bit platforms. You can easily install the pyodbc module on your machine using the pip install pyodbc command in Python interactive mode.


1 Answers

It doesn't support named parameters, but bound parameters passed in the correct order are fairly straightforward:

x = "This"
y = 345

mssql_cur.execute("SELECT * FROM mytable WHERE colx = ? AND coly = ?", x, y)

or

mssql_cur.execute("SELECT * FROM mytable WHERE colx = ? AND coly = ?", (x, y))

More details and options here, such as passing executemany parameters:

https://github.com/mkleehammer/pyodbc/wiki/Cursor

Good luck!

like image 94
FlipperPA Avatar answered Oct 20 '22 17:10

FlipperPA