0

I want to select all data of several particular dates using following codes.

test_date = ('2012-08-04', '2013-08-19')
conn=sqlite3.connect(sqlite_file)
c=conn.cursor()
dat=c.execute("SELECT dat FROM dat_tbl WHERE date IN ? ", test_date)
dat_tuple=dat.fetchall()
conn.close()

It failed with error message

OperationalError: near "?": syntax error

I am wondering what is wrong here and how to fix it. Thanks.

Lei Hao
  • 708
  • 1
  • 7
  • 21

1 Answers1

0

The correct expression should be,

c.execute("SELECT dat FROM dat_tbl WHERE date IN (?, ?)", (date1, date2))

question marks should be wrapped with paranthesis.

However, you would also like to consider using BETWEEN.

UPDATE

string.join(sequence) might help you automatically inject question marks to you query.

Consider below,

>>> ', '.join(['?']*5)
'?, ?, ?, ?, ?'

Thus,

>>> "SELECT * FROM example WHERE id in ({0})".format(', '.join(['?'] * len([1,3])))
'SELECT * FROM example WHERE id in (?, ?)'

or,

>>> q = "SELECT dat FROM dat_tbl WHERE date IN ({0})".format(', '.join(['?'] * len(test_date)))
>>> q
'SELECT dat FROM dat_tbl WHERE date IN (?, ?)'
marmeladze
  • 6,468
  • 3
  • 24
  • 45
  • What if I have 100 dates? Is there an alternative than 100 question marks? – Lei Hao Feb 27 '18 at 06:38
  • I've updated my answer. I thought you were be able to handle this to your own. This is beyond of sqlite3 scope - but verily connected to python string manipulation skills. – marmeladze Feb 27 '18 at 07:18