Jason Owens
Jason Owens

Reputation: 543

I need to run an if statement on an sql query, with variable provided or empty

I understand basically that my SQL statement will not run if it has no variable listed, because what I want do do is check to see if a name exists before writing to it (I can probably do this within SQL). I understand the issue, just not how to correct it... Figured I'd ask now before it's 9:30pm and I'm still digging around the issue. Thanks

app.py

import sqlite3
from sqlalchemy.orm import sessionmaker
from tabledef import *
engine = create_engine('sqlite:///tutorial.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

USERNAME = "Jas"
PASSWORD = "Booger"
EMAIL = "[email protected]"
AMOUNT = "500"
reg = User(USERNAME, PASSWORD, EMAIL, AMOUNT)

conn = sqlite3.connect("tutorial.db")
c = conn.cursor()
try:
    c.execute('SELECT username from users WHERE username = "%s"' % USERNAME)
    result = str(c.fetchall()).split("'")[1]
    print result
except ValueError as e:
    print e

Error message

Traceback (most recent call last):
  File "C:/Users/sysadmin/PycharmProjects/bet1/app3.py", line 18, in <module>
    result = str(c.fetchall()).split("'")[1]
IndexError: list index out of range

Upvotes: 0

Views: 917

Answers (1)

Lunaweaver
Lunaweaver

Reputation: 206

Not quite sure what you're asking, but I suggest you read the following section from the Python manual:

# 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()

In addition to preventing SQL injection attacks, it also uses fetchone() instead of... converting your response to a string and parsing it again.

Upvotes: 1

Related Questions