Python: How can I troubleshoot this Function? - python

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"')

Related

python sqlite code works but i get some errors

I wrote some code to learn SQL databases. My code works fine like I want it to. But I get this error and want to learn what is that.
import sqlite3
con = sqlite3.connect("items.db")
cursor = con.cursor()
cursor.execute("Create table if not exists weapons (name TEXT,ilvl TEXT,source TEXT)")
weapons_txt = open("C:\\Users\\kaytu\\Desktop\\Python\\Exercises\\weapons.txt","r")
for i in weapons_txt:
cursor.execute("Insert into weapons values(?,?,?)",(i.split(";")[0],i.split(";")[1],i.split(";")[2],))
con.commit()
weapons_txt.close()
con.close()
Traceback (most recent call last):
File "c:\Users\kaytu\Desktop\Python\Exercises\Testing.py", line 9, in <module>
cursor.execute("Insert into weapons values(?,?,?)",(i.split(";")[0],i.split(";")[1],i.split(";")[2],))
IndexError: list index out of range
And why do i get the "..." string after every source text? printscreen
this means that at least one of the lines in the txt file has less than two semicolons, check all the lines of the file again

Python SQLite3 won't execute wildcard for variable

I have created a database with sqlite3, but I can't access and retrieve data by using wildcards.
To retrive the h1 column with the value: Case Samsung Galaxy S9, the wildcard '%?%' doesn't work.
I get the error:
Traceback (most recent call last):
File "regex_query.py", line 13, in <module>
for row in c.execute("SELECT * FROM products WHERE h1 LIKE '%?%' ORDER BY price", (t,)):
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 0, and there are 1 supplied.
This is my code. I tried various iterations the query, but none of them seem to work.
For debugging I also inserted the string "Samsung" straight into the query and it works. By only proble is that
import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()
t = 'Samsung'
for row in c.execute("SELECT * FROM products WHERE h1 LIKE '%?%' ORDER BY price", (t,)):
print row
print c.fetchall()
I have been looking for a solution for hours, but I can't locate where the problem is. Thanks.
I don't think that method works unless you're using a sql that needs VALUES. This should work though
for row in c.execute("SELECT * FROM products WHERE h1 LIKE '%{}%' ORDER BY price".format(t))

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.

Sqlite/Python simple issue when searching DB

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

"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

Categories

Resources