How to test if a table already exists? - python

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)

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

Problem with database row and column selection <sqlite3.Row object at 0x000001DE5B746D50> getting this wierd return

hii when i was trying to do a project on database management using sqlite i face this problem. the code is
import sqlite3
class DBConnect():
def __init__(self):
self.db=sqlite3.connect("Registrations.db")
self.db.row_factory=sqlite3.Row
self.db.execute("create table if not exists Ticket(ID integer Primary key autoincrement,name text,gender text,comment text)")
self.db.commit()
def Add(self,Name,gender,comment):
self.db.row_factory=sqlite3.Row
self.db.execute("insert into Ticket(name,gender,comment) values(?,?,?)",(Name,gender,comment))
self.db.commit()
return "DATA ADDED SUCCESFULLY"
def Show(self):
self.db.row_factory = sqlite3.Row
cursor=self.db.execute("select * from Ticket").fetchall()
print(type(cursor))
return cursor
Iam not getting any row data instead i get the address where it is stored like this <sqlite3.Row object at 0x000001DE5B746D50>
I think you are trying to print the contents of the row i.e Name Gender etc but instead ended up printing the type of the object print(type(cursor)) which is <sqlite3.Row object at 0x000001DE5B746D50>.
To print the contents of the row you can try print(cursor)

Operational error no such column SQLite 3

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

How to return a specific list from the record in a table?

Write a function named "filtered_records" that doesn't take any parameters and returns a list. There is a database saved in a file named "solar.db" containing a table named "worry" with columns "hip", "log", and "convention" each storing integer values. Return a list containing each record in the table with a "log" value greater than 59.
import sqlite3
def filtered_records():
conn = sqlite3.connect('solar.db')
c = conn.cursor()
confirm_list = c.execute('SELECT log FROM worry').fetchall()
return [list(i) for i in confirm_list if i > 59]
conn.commit()
Here is my attempt at the problem. What am I doing wrong?
You have to filter your query in sql. Moreover you don't need to call commit when you just select rows from database, you should use commit function only when you want to insert data to database, here you can read more about transactions
import sqlite3
def filtered_records():
conn = sqlite3.connect('solar.db')
c = conn.cursor()
confirm_list = c.execute('SELECT hip, log, convention FROM worry WHERE log > 59').fetchall()
return confirm_list

TypeError: 'NoneType' object is not iterable

I need to process mysql data one row at a time and i have selected all rows put them in a tuple but i get the error above.
what does this mean and how do I go about it?
Provide some code.
You probably call some function that should update database, but the function does not return any data (like cursor.execute()). And code:
data = cursor.execute()
Makes data a None object (of NoneType). But without code it's hard to point you to the exact cause of your error.
It means that the object you are trying to iterate is actually None; maybe the query produced no results?
Could you please post a code sample?
The function you used to select all rows returned None. This "probably" (because you did not provide code, I am only assuming) means that the SQL query did not return any values.
Try using the cursor.rowcount variable after you call cursor.execute(). (this code will not work because I don't know what module you are using).
db = mysqlmodule.connect("a connection string")
curs = dbo.cursor()
curs.execute("select top 10 * from tablename where fieldA > 100")
for i in range(curs.rowcount):
row = curs.fetchone()
print row
Alternatively, you can do this (if you know you want ever result returned):
db = mysqlmodule.connect("a connection string")
curs = dbo.cursor()
curs.execute("select top 10 * from tablename where fieldA > 100")
results = curs.fetchall()
if results:
for r in results:
print r
This error means that you are attempting to loop over a None object. This is like trying to loop over a Null array in C/C++. As Abgan, orsogufo, Dan mentioned, this is probably because the query did not return anything. I suggest that you check your query/databse connection.
A simple code fragment to reproduce this error is:
x = None
for each i in x:
#Do Something
pass
This may occur when I try to let 'usrsor.fetchone' execute twice. Like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
if cursor.fetchone() is not None:
username, password = cursor.fetchone()
print username, password
I don't know much about the reason. But I modified it with try and except, like this:
import sqlite3
db_filename = 'test.db'
with sqlite3.connect(db_filename) as conn:
cursor = conn.cursor()
cursor.execute("""
insert into test_table (id, username, password)
values ('user_id', 'myname', 'passwd')
""")
cursor.execute("""
select username, password from test_table where id = 'user_id'
""")
try:
username, password = cursor.fetchone()
print username, password
except:
pass
I guess the cursor.fetchone() can't execute twice, because the cursor will be None when execute it first time.
I know it's an old question but I thought I'd add one more possibility. I was getting this error when calling a stored procedure, and adding SET NOCOUNT ON at the top of the stored procedure solved it. The issue is that earlier selects that are not the final select for the procedure make it look like you've got empty row sets.
Try to append you query result to a list, and than you can access it. Something like this:
try:
cursor = con.cursor()
getDataQuery = 'SELECT * FROM everything'
cursor.execute(getDataQuery)
result = cursor.fetchall()
except Exception as e:
print "There was an error while getting the values: %s" % e
raise
resultList = []
for r in result:
resultList.append(r)
Now you have a list that is iterable.

Categories

Resources