sqlite3 view() prints with empty list? - python

I have testtable() function that works to create the table if necessary and list all the PDF file names in a column. However, when I execute my view() function, it prints an empty list. Am I missing something or just going about this in the wrong way?
import os, sys
import sqlite3
import csv
testdb = 'pdftestdir.db'
def testtable():
conn = sqlite3.connect(testdb)
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS test (name TEXT)')
path = os.listdir('/root/Desktop/PDF')
conn = sqlite3.connect(testdb)
cur = conn.cursor()
cur.execute('SELECT * FROM test')
exists = cur.fetchall()
for name in path:
if name.endswith('.pdf'):
if not exists:
cur.execute('INSERT INTO test VALUES (?)', (name,))
else:
pass
conn.commit()
conn.close()
def view():
conn = sqlite3.connect(testdb)
cur = conn.cursor()
cur.execute('SELECT * FROM test')
cur.fetchall()
rows = cur.fetchall()
conn.close()
print(rows)

You unnecessarily call cur.fetchall() without storing the returning value to a variable, and the cursor has already reached the end of the rows returned with that call, so the second time you call cur.fetchall() it no longer has any more rows to return.
You can fix this by simply removing the redundant call.
Change:
cur.fetchall()
rows = cur.fetchall()
to:
rows = cur.fetchall()

Related

Python SQLite query always returns None

I have a SQL-file (SQLite format 3) that I can query with the DB Browser for SQLite (Windows). Whenever I use Python to access the db I get a Null result.
import sqlite3
conn = sqlite3.connect('C:/tmp/test.sql')
cursor = conn.cursor()
conn.execute('select count(*) from Player')
print("result is:", cursor.fetchone()) # result is: None
Every Select statement leads to "result is: None".
Any ideas?
Bart.
import sqlite3
connection = sqlite3.connect(database_name)
cursor = connection.cursor()
cursor.execute("select val from table_name where x = 'something';")
result = cursor.fetchone()
# directly returning result also gives null
if result:
return result[0] # tuple returned in result
cursor.close()
connection.close()

Basic Database made with SQLITE3

I created a basic database in python with sqlite3 which takes in 3 values and stores them. Now where the problem lies is that when I created a function that is supposed to output the values, no syntax errors were displayed on terminal and none of my values were printed. Im guessing this is a minor error but I am not able to spot it.
The code is given below:
import sqlite3
def create_table():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity
INTEGER, price FLOAT)")
conn.commit()
conn.close()
def insert(item, quantity, price):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("INSERT INTO store VALUES ('?, ?, ?')", (item, quantity,
price))
conn.commit()
conn.close()
insert("Mug", 8, 6)
def view():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
conn.close()
return rows
print(view())
Again no error messages were displayed but my values are not displayed.
I have tried it. it seems the single quotes are not needed in the insert. See modified below:
import sqlite3
def create_table():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price FLOAT)")
conn.commit()
conn.close()
def insert(item, quantity, price):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("INSERT INTO store VALUES (?,?,?)", (item, quantity, price))
conn.commit()
conn.close()
def view():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
conn.close()
return rows
create_table()
insert("Mug", 1, 5)
print(view())

Inserting into Postgres DB column with python

conn = psycopg2.connect("dbname=name host=host user=user password=pass port=port")
cur = conn.cursor()
with open('big shot.json') as f:
data = json.load(f)
for key in data["permissions"]:
cur.execute("INSERT INTO permissions (name) VALUES (%s);", (key,))
conn.commit()
output = cur.execute("SELECT * FROM permissions")
print(output)
I have this that I'm trying to use to create new rows in my database, but it doesn't do anything. It doesn't return any errors, but it also doesn't write to my database, and output, obviously, returns "None" in the console.
You need to fetch the data from the cursor:
cur.execute("SELECT * FROM permissions")
data = cur.fetchall()
print(data)

creating a table in sqlite3 python

I apologize in advance for asking such a basic question but I am new to SQlite3 and having trouble starting. I am trying to build a database with one table. I used the following code to build a table.
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE mytable
(start, end, score)''')
but whenever I try to update or access the table it seems that it doesnt exist or maybe it exists in a different database. I also tried creating a table called example.mytable but I got the error:
sqlite3.OperationalError: unknown database example
What am I missing?
Thanks
I think that a commit is needed after inserts (schema changes such as new tables should automatically commit). I would suggest adding the full path to your database as well to make sure you are accessing the same location next time round.
Here is an extension on your code:
import sqlite3
def create():
try:
c.execute("""CREATE TABLE mytable
(start, end, score)""")
except:
pass
def insert():
c.execute("""INSERT INTO mytable (start, end, score)
values(1, 99, 123)""")
def select(verbose=True):
sql = "SELECT * FROM mytable"
recs = c.execute(sql)
if verbose:
for row in recs:
print row
db_path = r'C:\Users\Prosserc\Documents\Geocoding\test.db'
conn = sqlite3.connect(db_path)
c = conn.cursor()
create()
insert()
conn.commit() #commit needed
select()
c.close()
Output:
(1, 99, 123)
After closing the program if I log onto the SQLite database the data is still there.
import sqlite3;
import pandas as pd;
con=None
def getConnection():
databaseFile="./test.db"
global con
if con == None:
con=sqlite3.connect(databaseFile)
return con
def createTable(con):
try:
c = con.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS Movie
(start, end, score)""")
except Exception as e:
pass
def insert(con):
c = con.cursor()
c.execute("""INSERT INTO Movie (start, end, score)
values(1, 99, 123)""")
def queryExec():
con=getConnection()
createTable(con)
insert(con)
# r = con.execute("""SELECT * FROM Movie""")
result=pd.read_sql_query("select * from Movie;",con)
return result
r = queryExec()
print(r)

UnboundLocalError: local variable 'rows' referenced before assignment

i'm trying to make a database connection by an other script.
But the script didn't work propperly.
and if I do a 'print' on the rows then I get the value 'null'
But if I use a 'select * from incidents' query then i get the result from the table incidents.
import database
rows = database.database("INSERT INTO incidents VALUES(3 ,'test_title1', 'test', TO_DATE('25-07-2012', 'DD-MM-YYYY'), CURRENT_TIMESTAMP, 'sector', 50, 60)")
#print database.database()
print rows
database.py script:
import psycopg2
import sys
import logfile
def database(query):
logfile.log(20, 'database.py', 'Executing...')
con = None
try:
con = psycopg2.connect(database='incidents', user='ipfit5', password='test')
cur = con.cursor()
#print query
cur.execute(query)
rows = cur.fetchall()
con.commit()
#test row does work
#cur.execute("INSERT INTO incidents VALUES(3 ,'test_titel1', 'test', TO_DATE('25-07-2012', 'DD-MM-YYYY'), CURRENT_TIMESTAMP, 'sector', 50, 60)")
except:
logfile.log(40, 'database.py', 'Er is iets mis gegaan')
logfile.log(40, 'database.py', str(sys.exc_info()))
finally:
if con:
con.close()
return rows
Since you are not declaring "rows" before your "try:" block it will not be defined if there is an exception. Try putting rows = [] above try.

Categories