Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using cursor.execute arguments in pymssql with IN sql statement

I have troubles using a simple sql statement with the operator IN through pymssql.

Here is a sample :

import pymssql
conn = pymssql.connect(server='myserver', database='mydb')
cursor = conn.cursor()
req = "SELECT * FROM t1 where id in (%s)"
cursor.execute(req,  tuple(range(1,10)))
res = cursor.fetchall()

Surprisingly only the first id is returned and I can't figure out why. Does anyone encounter the same behavior ?

like image 925
Alex Avatar asked Sep 03 '15 20:09

Alex


People also ask

What is cursor execute in SQL?

This method executes a SQL query against the database. This is a DB API compliant call. Parameters are substituted using question marks, e.g. "SELECT name FROM table WHERE id=?". The parameter args is a tuple . It returns None on success or raises an exception in the case of an error.

Can Pymysql connect to SQL Server?

The pymssql. connect function is used to connect to SQL Database.

What is Pymssql in Python?

A simple database interface for Python that builds on top of FreeTDS to provide a Python DB-API (PEP-249) interface to Microsoft SQL Server. The 2. x branch of pymssql is built on the latest release of FreeTDS which removes many of the limitations found with older FreeTDS versions and the 1. x branch.


1 Answers

You're trying to pass nine ID values to the query and you only have one placeholder. You can get nine placeholders by doing this:

ids = range(1,10)
placeholders = ','.join('%s' for i in ids)
req = "SELECT * FROM t1 where id in ({})".format(placeholders)
cursor.execute(req, ids)
res = cursor.fetchall()

As an aside, you don't necessarily need a tuple here. A list will work fine.

like image 59
mechanical_meat Avatar answered Sep 27 '22 23:09

mechanical_meat