Sqlite/Python simple issue when searching DB - python

Hello I am having a bit of a dumbo problem. I am trying to search a DB for an ID number. The problem I am running into in when I enter a ID number that does not exist the program crashes. I will post my code under and try to explain where I am at. I am using SQlite with Python3.
cur = con.cursor()
cur.execute("SELECT * FROM coupons WHERE id_num=:id_num",
{"id_num": input_value})
con.commit()
row = cur.fetchone()
#Verifying that the ID exists for later in the program.
if input_value == row[0]:
bad_code = False
I know my programming is somewhat amateurish but I am still learning the ropes.
The error is as follows:
Traceback (most recent call last):
File "Z:/Python_Programs/data_bases/coupon_scanner_v8.py", line 217, in <module>
verify_barcode(user_code);
File "Z:/Python_Programs/data_bases/coupon_scanner_v8.py", line 87, in verify_barcode
startDay = row[1]
TypeError: 'NoneType' object is not subscriptable
I will continue to do research to solve this problem. Thank you!!!

fetchone() returns None if there are no more values to fetch from the cursor - in your case, where the id doesn't exist. So, in order to check if the id existed you should do something down these lines:
row = cur.fetchone()
# Verifying that the ID exists for later in the program.
if row is not None:
bad_code = False

Related

How can I handle the failure of a DELETE statement to delete any rows?

I wrote this code to delete a row from a table – but if I enter a name which is not in the table, it still outputs "Data Deleted Successfully":
n = input("Enter Student name you want to delete:")
try:
cur.execute('DELETE FROM studentdata WHERE name=?', (n,))
print("Data Deleted Successfully")
conn.commit()
except:
print("No data found with this name: ")
How can I handle this properly?
Cursor.execute() will only raise an exception if the SQL statement it attempts to execute fails – for example:
>>> cur.execute("This is not SQL")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: near "This": syntax error
or
>>> cur.execute("SELECT * FROM nonexistent_table;")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: no such table: nonexistent_table
A valid SQL statement which correctly does nothing has succeeded, not failed, and so doesn't raise an exception. Your DELETE statement is correct to do nothing when it doesn't find the provided value for name, so there's no error.
You can find out how many rows were affected by an SQL statement using the Cursor.rowcount attribute. Rewriting your code to make use of the attribute would look something like this:
name = input("Enter Student name you want to delete:")
cur.execute('DELETE FROM studentdata WHERE name = ?;', [name])
if cur.rowcount > 0:
print("Data Deleted Successfully")
conn.commit()
else:
print("No data found with this name:", name)
Note: I've left the commit() where it was in your code … depending on your application, it may be that it should in fact be moved outside the if/else block.

Python: How can I troubleshoot this Function?

I'm working on an application and currently focusing on the database area.
I have successfully setup functions that create databases and write to them, however right now I am trying to retrieve specific rows from the database however NO MATTER WHAT I TRY I always get a syntax error DESPITE my SQL query running successfully in in sqlite browser.
This is my trouble code:
def findapple():
conn = sqlite3.connect('working.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM "working" WHERE "symbol" = 'aapl';')
print row
If I understand the code I've written, it should connect to "working.db" create a cursor for the database then for each row that match my query it should be printed to the console.
Can anyone please help shed some light on this?
Thank you!
Current Code Per comments below:
def findapple():
conn = sqlite3.connect('working.db')
c = conn.cursor()
for row in c.execute('SELECT * FROM working WHERE symbol = 'aapl'')
print row
and the error output:
Traceback (most recent call last):
File "main.py", line 1, in <module>
from stock import *
File "/Users/ME/Documents/Code/Stocks/stock/database.py", line 61
for row in c.execute('SELECT * FROM working WHERE symbol = 'aapl'')
Your string syntax is wrong:
c.execute('SELECT * FROM working WHERE symbol = "aapl"')

Python to SQLite3

I am making a project where I connect to a database with Python then update and change things. I have run into problems when trying to retrieve information.
I am using this code:
import sqlite3
conn = sqlite3.connect('Project.db')
print ("Opened database sucessfully")
cursor = conn.execute("SELECT ID,ResidentTitle,ResidentForname FROM Residents")
for row in cursor:
print ("ID = "), row[0]
print ("ResidentTitle ="), row[1]
print ("Name ="), row[2]
print ("done");
conn.close()
from this I am getting back the error:
Traceback (most recent call last):
File "C:/sqlite/Sqlplz.py", line 7, in <module>
cursor = conn.execute("SELECT ID,ResidentTitle,ResidentForname FROM Residents")
sqlite3.OperationalError: no such table: Residents
How can I resolve this error?
cursor = conn.execute("SELECT ID,ResidentTitle,ResidentForname FROMResidents")
-------------------------------------------------------------------^
You are missing space, you should update like that
cursor = conn.execute("SELECT ID,ResidentTitle,ResidentForname FROM Residents")
Problem is fixed, issue with a broken save file.

"IndexError: list index out of range" while charging MySQL DB

I get the following error code while executing my Code. The error does not occur immediately - it occurs randomly after 2-7 hours. Until the error occurs there is no problem to stream the online feeds and write them in a DB.
Error message:
Traceback (most recent call last):
File "C:\Python27\MySQL_finalversion\RSS_common_FV.py", line 78, in <module>
main()
File "C:\Python27\MySQL_finalversion\RSS_common_FV.py", line 63, in main
feed_iii = feed_load_iii(feed_url_iii)
File "C:\Python27\MySQL_finalversion\RSS_common_FV.py", line 44, in feed_load_iii
in feedparser.parse(feed_iii).entries]
IndexError: list index out of range
Here you can find my Code:
import feedparser
import MySQLdb
import time
from cookielib import CookieJar
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="root", # your username - SELECT * FROM mysql.user
passwd="****", # your password
db="sentimentanalysis_unicode",
charset="utf8") # name of the data base
cur = db.cursor()
cur.execute("SET NAMES utf8")
cur.execute("SET CHARACTER SET utf8")
cur.execute("SET character_set_connection=utf8")
cur.execute("DROP TABLE IF EXISTS feeddata_iii")
sql_iii = """CREATE TABLE feeddata_iii(III_ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(III_ID),III_UnixTimesstamp integer,III_Timestamp varchar(255),III_Source varchar(255),III_Title varchar(255),III_Text TEXT,III_Link varchar(255),III_Epic varchar(255),III_CommentNr integer,III_Author varchar(255))"""
cur.execute(sql_iii)
def feed_load_iii(feed_iii):
return [(time.time(),
entry.published,
'iii',
entry.title,
entry.summary,
entry.link,
(entry.link.split('=cotn:')[1]).split('.L&id=')[0],
(entry.link.split('.L&id=')[1]).split('&display=')[0],
entry.author)
for entry
in feedparser.parse(feed_iii).entries]
def main():
feed_url_iii = "http://www.iii.co.uk/site_wide_discussions/site_wide_rss2.epl"
feed_iii = feed_load_iii(feed_url_iii)
print feed_iii[1][1]
for item in feed_iii:
cur.execute("""INSERT INTO feeddata_iii(III_UnixTimesstamp, III_Timestamp, III_Source, III_Title, III_Text, III_Link, III_Epic, III_CommentNr, III_Author) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)""",item)
db.commit()
if __name__ == "__main__":
while True:
main()
time.sleep(240)
If you need further information - please feel free to ask. I need your help!
Thanks and Regards from London!
In essence, your program is insufficiently resilient to poorly-formatted data.
Your code makes very explicit assumptions about the structure of the data, and is unable to cope if the data is not so structured. You need to detect the cases where the data is incorrectly formatted and take some other action then.
A rather sloppy way to do this would simply trap the exception that's currently being raised which you could do with (something like)
try:
feed_iii = feed_load_iii(feed_url_iii)
except IndexError:
# do something to report or handle the data format problem

With Python and SQLite, how do i read an item from the database into a variable?

I am a programming beginner, and would like to get a little help with learning SQLite and Python.
Currently, I have a database called "Status.db" which contains two columns. These columns are "stamp", type INT, and "messages", type TEXT, consecutively.
The code I am using to try to read one instance of messages, with a particular stamp, ID, into a variable "output" is as follows:
#cherrypy.expose
def comment(self, ID = None):
con = lite.connect('static/database/Status.db')
with con:
cur = con.cursor()
cur.execute("SELECT messages FROM Status WHERE stamp is ?", (ID,))
temp = cur.fetchone()
output = temp[0]
However, when i execute this code, I get an error message that reads:
Traceback (most recent call last):
File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 606, in respond
cherrypy.response.body = self.handler()
File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 25, in __call__
return self.callable(*self.args, **self.kwargs)
File "proj1base.py", line 176, in comment
output = temp[0]
TypeError: 'NoneType' object is not subscriptable
I am wondering if anyone could clarify to me what this error means, and what i could do to make it work.
Thanks in advance!
EDIT:
Here is the code that created and writes into the database
#cherrypy.expose
def writeStatus(self, newStatus=None, post=None):
"""Update the status file with the most recent status update
by inserting a timestamp and new status into a database
"""
con = lite.connect('static/database/Status.db')
stamp = time()
with con:
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS Status(stamp INT, messages TEXT)")
cur.execute("INSERT INTO Status VALUES(?, ?)", (stamp, newStatus))
That means that fetchone() is returning None, which means that your SQL query isn't returning any result rows.
This is probably because you should use = instead of is in your SQL:
SELECT messages FROM Status WHERE stamp = ?

Categories

Resources