Operational error no such column SQLite 3 - python

I've struggled with this for long. I can only get query results from the first column, all the other columns return "No such column" What could be the problem. I'm new to python and sqlite3...
cur.execute('''CREATE TABLE IF NOT EXISTS learner_data(ADM INT NOT NULL,NAME TEXT NOT NULL,CLASS TEXT NOT NULL,STREAM TEXT NOT NULL,CATEGORY TEXT NOT NULL,GENDER TEXT NOT NULL,COUNTY TEXT NOT NULL,PARENT TEXT NOT NULL,PARENT_CONTACT TEXT NOT NULL,PRIMARY KEY(CLASS,STREAM,CATEGORY,NAME,ADM))''')
Select failing:
SELECT * FROM learner_data WHERE CLASS is FORM_II

From your comment: ...WHERE CLASS is FORM_II...
You cannot use is here, you should use =. And, not quoting FORM_II means that you're trying to find rows where the value is the same for the columns CLASS and FORM_II (but the latter isn't a column so this will always render 0 matches), instead of looking for the value FORM_II.
So, try SELECT * FROM learner_data WHERE CLASS = 'FORM_II'

def fetch_learner_data_from_combo(self):
new = str("self.stream_combo.currentText()")
connection= sqlite3.connect("mydb.db")
query = ("SELECT * FROM learner_data WHERE STREAM = new")
result = connection.execute(query)
self.marks_table.setRowCount(0)
for row_number,row_data in enumerate(result):
self.marks_table.insertRow(row_number)
for column_number,data in enumerate(row_data):
self.marks_table.setItem(row_number,column_number,QTableWidgetItem(str(data)))
connection.commit()
connection.close()

Related

show sqlite data in several window

I want to know how can I use one data in several windows with python, Tkinter
this is my code for creating the database
def connect():
conn = sqlite3.connect("../database.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY , name text , price INTEGER )"
)
conn.commit()
conn.close()
connect()
and this my code for get data and show :
def clear_item_list():
items.delete(0, END)
def fill_item_list(items):
for item_ in items:
items.insert(END, item_)
def item_list_view():
clear_item_list()
items = app.manager.data_1.view()
fill_item_list(items)
I when I want to run project I get an error: 'str' object cannot be interpreted as an integer
I don't know what to do if you can, please help me

Having some trouble with Tkinter Treeview and SQLite when trying to search for a name in a database

I have successfully been able to click a search button on my tkinter GUI and have the results display in my treeview however if I want to search straight again I get an error because when trying to write for the second time it's writing to the same row as the first search query. How would I either clear the treeview or make sure that my program writes to the next row in my treeview?
srchEntry = str(searchEntry.get())
conn = sqlite3.connect('test.db')
c = conn.cursor()
c.execute("SELECT memberID, fullName, username FROM Test WHERE fullName ='"+srchEntry+"'")
conn.commit()
data = c.fetchall()
treeview.insert("", 0, 1, values=(str(data[0][0]), str(data[0][1]), str(data[0][2])))
So 'data' will return ('memberID', 'fullname', 'username') and I am inserting those values into my treeview
Read doc Treeview.insert.
insert() has parameter index to choose row. Or you can use word end to put after last row.
delete() needs id of inserted row/item (not row number)
item_id = treeview.insert(...)
and later
treeeview.delete(item_id)

python cursor.execute returning empty

I have a problem with my python code which I want to use for a REST API server.
The current problem is that my database query is returning null when I know that the value is there
The code for the specific path:
#app.route('/data/active_predicted/<int:ticketId>', methods=['GET'])
def search_db_tickId_act(ticketId):
cursor = db.cursor()
db_query = cursor.execute("select * from active_predicted where ticketId=" + str(ticketId))
json_output = json.dumps(dict(cursor.fetchall()))
cursor.close()
if not cursor.fetchall():
return "Nothing found \n SQL Query: " + "select * from active_predicted where ticketId=" + str(ticketId)
else:
return str(cursor.fetchall())
When I access this URL I get returned the following:
Nothing found SQL Query: select * from active_predicted where ticketId=1324
When I plug this SQL query I get the result I want, 1 row with 2 columns but it seems as though the program cannot locate the row?
The problems:
As #pvg mentioned, you need to escape your input values when querying database;
If you want to fetch a dictionary-like result, passing dictionary=True when you initialize the cursor;
In your original code, you didn't return the variable json_output;
To fetch only one result, use fetchone instead fetchall;
After cursor.close() got called, you can obtain nothing from that cursor no matter you fetched before or not;
Use try-finally to ensure that cursor always get closed (at last).
Here's the fixed code:
#app.route('/data/active_predicted/<int:ticketId>', methods=['GET'])
def search_db_tickId_act(ticketId):
try:
cursor = db.cursor(dictionary=True)
db_query = cursor.execute("select * from active_predicted where ticketId=%s LIMIT 1", ticketId)
row = cursor.fetchone()
if row:
return json.dumps(row)
else:
return "Nothing found \n SQL Query: " + "select * from active_predicted where ticketId=" + str(ticketId)
finally:
cursor.close()

How to test if a table already exists?

I'm working on a scrabblecheat program
Following some examples I have the following code below which uses SQLite for a simple database to store my words.
However it tells me I can't recreate the database table.
How do I write in a check for if there is already a table named spwords, then skip trying to create it?
The error:
(<class 'sqlite3.OperationalError'>, OperationalError('table spwords already exists',), None)
The Code:
def load_db(data_list):
# create database/connection string/table
conn = sqlite.connect("sowpods.db")
#cursor = conn.cursor()
# create a table
tb_create = """CREATE TABLE spwords
(sp_word text, word_len int, word_alpha text, word_score int)
"""
conn.execute(tb_create) # <- error happens here
conn.commit()
# Fill the table
conn.executemany("insert into spwords(sp_word, word_len, word_alpha, word_score) values (?,?,?,?)", data_list)
conn.commit()
# Print the table contents
for row in conn.execute("select sp_word, word_len, word_alpha, word_score from spwords"):
print (row)
if conn:
conn.close()
The query you're looking for is:
SELECT name FROM sqlite_master WHERE type='table' AND name='spwords'
So, the code should read as follows:
tb_exists = "SELECT name FROM sqlite_master WHERE type='table' AND name='spwords'"
if not conn.execute(tb_exists).fetchone():
conn.execute(tb_create)
A convenient alternative for SQLite 3.3+ is to use a more intelligent query for creating tables instead:
CREATE TABLE IF NOT EXISTS spwords (sp_word text, word_len int, word_alpha text, word_score int)
From the documentation:
It is usually an error to attempt to create a new table in a database that already contains a table, index or view of the same name. However, if the "IF NOT EXISTS" clause is specified as part of the CREATE TABLE statement and a table or view of the same name already exists, the CREATE TABLE command simply has no effect (and no error message is returned). An error is still returned if the table cannot be created because of an existing index, even if the "IF NOT EXISTS" clause is specified.
conn = sqlite3.connect('sowpods.db')
curs = conn.cursor()
try:
curs.execute('''CREATE TABLE spwords(sp_word TEXT, word_len INT, word_alpha TEXT,word_score INT)''')
conn.commit()
except OperationalError:
None
https://docs.python.org/2/tutorial/errors.html
I believe if it already exists you can just skip the error and move directly into the inserting of the data
I am not a fan of the bounce the CREATE off the database approach. You should know whether the table exists so that first time initialization can occur.
Here is the same query based answer but based on general purpose functions:
def getTables(conn):
"""
Get a list of all tables
"""
cursor = conn.cursor()
cmd = "SELECT name FROM sqlite_master WHERE type='table'"
cursor.execute(cmd)
names = [row[0] for row in cursor.fetchall()]
return names
def isTable(conn, nameTbl):
"""
Determine if a table exists
"""
return (nameTbl in getTables(conn))
Now the top code is
if not(isTable(conn, 'spwords')):
# create table and other 1st time initialization
Here is an example that shows how to cleanly consume the result from fetchone() call:
table_exists(conn:sqlite3.Connection, tbl_name:string) -> bool:
(count,) = conn.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{}'".format(tbl_name)).fetchone()
return (count > 0)

Insert data instead of drop table into mysql

I'm attempting to get a python script to insert data into a database without having it drop the table first.. I'm sure this isn't hard to do but I can't seem to get the code right..
Here is the full python script..
#!/usr/bin/python
# -*- coding: utf-8 -*-
import requests
import hashlib
import time
import MySQLdb
#Dont forget to fill in PASSWORD and URL TO saveTemp (twice) in this file
sensorids = ["28-000004944b63", "28-000004c01b2c"]
avgtemperatures = []
for sensor in range(len(sensorids)):
temperatures = []
for polltime in range(0,3):
text = '';
while text.split("\n")[0].find("YES") == -1:
# Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before.
tfile = open("/sys/bus/w1/devices/"+ sensorids[sensor] +"/w1_slave")
# Read all of the text in the file.
text = tfile.read()
# Close the file now that the text has been read.
tfile.close()
time.sleep(1)
# Split the text with new lines (\n) and select the second line.
secondline = text.split("\n")[1]
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
temperaturedata = secondline.split(" ")[9]
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
temperature = float(temperaturedata[2:])
# Put the decimal point in the right place and display it.
temperatures.append(temperature / 1000 * 9.0 / 5.0 + 32.0)
avgtemperatures.append(sum(temperatures) / float(len(temperatures)))
print avgtemperatures[0]
print avgtemperatures[1]
#connect to db
db = MySQLdb.connect("localhost","user","password","temps" )
#setup cursor
cursor = db.cursor()
#create temps table
cursor.execute("DROP TABLE IF EXISTS temps")
sql = """CREATE TABLE temps (
temp1 FLOAT,
temp2 FLOAT )"""
cursor.execute(sql)
#insert to table
try:
cursor.execute("""INSERT INTO temps VALUES (%s,%s)""",(avgtemperatures[0],avgtemperatures[1]))
db.commit()
except:
db.rollback()
#show table
cursor.execute("""SELECT * FROM temps;""")
print cursor.fetchall()
((188L, 90L),)
db.close()
This is the part I need assistance with..
If I have it drop the table it works fine but I don't want it to drop the table, just insert the new data into the same table.
#connect to db
db = MySQLdb.connect("localhost","user","pasword1","temps" )
#setup cursor
cursor = db.cursor()
#create temps table
cursor.execute("DROP TABLE IF EXISTS temps")
sql = """CREATE TABLE temps (
temp1 FLOAT,
temp2 FLOAT )"""
cursor.execute(sql)
#insert to table
try:
cursor.execute("""INSERT INTO temps VALUES (%s,%s)""",(avgtemperatures[0],avgtemperatures[1]))
db.commit()
except:
db.rollback()
#show table
cursor.execute("""SELECT * FROM temps;""")
print cursor.fetchall()
((188L, 90L),)
db.close()
You shouldn`t have to drop a table each time you want to enter data. In fact, it defeats the whole purpose of the database since you will remove all the previous data each time you run your script.
You should ask to create the table but only if it does not exists. Use the following.
sql = """CREATE TABLE IF NOT EXISTS temps (
temp1 FLOAT,
temp2 FLOAT )"""
cursor.execute(sql)
I've had this problem with updating. Try adding COMMIT to the end of your sql. I use psycopg2 to connect to a postgresql database. Here is an example.
def simple_insert():
sql = '''INSERT INTO films VALUES ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes'); COMMIT;'''
try:
conn = psycopg2.connect(database)
cur = conn.cursor()
cur.execute(sql)
except:
raise
I think your problem is your not saving the transaction and the COMMIT command should fix it.

Categories

Resources