-2

For my program I need to link two tables together which I know how to do. However, I only need to select certain fields and they are already stored in a python variable. How can I execute an sql search with only selects the fields from the row containing that variable value?

I am using SQLite and all I can do at the moment is something like

sql1 = '''SELECT *
FROM Dogs INNER JOIN Owners
ON Dogs.DogID = Owners.DogID
Order By Speed desc;
'''

I need to be able to use a variable

Ben Dent
  • 37
  • 1
  • 7

3 Answers3

3

Python manuals should be the primary information source. The standard library directly provides a Sqlite interface with nice examples.

One example just reads as:

# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

# Do this instead
t = ('RHAT',)
c.execute('SELECT * FROM stocks WHERE symbol=?', t)
print c.fetchone()

With your own code, it gives:

sql1 = '''SELECT *
FROM Dogs INNER JOIN Owners
ON Dogs.DogID = Owners.DogID
WHERE Dogs.DogID = ?
Order By Speed desc;
'''
c.execute(sql1, dogid)
...
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • I get an error message when specifying variable above that then using what you said as apparently it uses 1 binding but 7 are supplied – Ben Dent Aug 23 '15 at 12:51
  • @BenDent Is `DogID` a string of 7 characters? Then you most probably forgot to provide it as a 1-tuple, ie. `c.execute(sql1, (dogid,))`. – lenz Aug 23 '15 at 13:12
0

You can search in a SQL database like this:

import sqlite3

db = sqlite3.connect('db.sq3')
cursor = db.cursor()

to_search = ('value', )
found = cursor.execute('SELECT * FROM table WHERE key=?', to_search).fetchall()
Texom512
  • 4,785
  • 3
  • 16
  • 16
0

A little example of string formatting in python:

sql1 = '''SELECT * {0}
FROM {1} INNER JOIN {2}
ON {1}.{3} = {2}.{3}
Order By {4} desc;
'''

print(sql1.format('Spot','Dogs', 'Owners', 'DogID', 'Speed'))
primero
  • 591
  • 1
  • 6
  • 17