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
Related
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)
I am currently trying to make a command line todo manager that will allow the user to input a task(s), remove it and list the task(s) out. From what I tried visualizing it didn't do as I thought it would, it's my first time using sqlite3.
What I am trying to achieve:
Storing the task(s) in the database which will automatically add an incrementing ID to it.
Example:
python todo.py -add do the laundry on Sunday
[in the database]
Id Task
1 do the laundry on Sunday
My code.
import sqlite3
import argparse
def parse_args():
desc = 'Todo manager for storing and removing tasks'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument("-a", "--add", "-add", help="To add a new item to the list",
type=str, nargs="+")
parser.add_argument("-r", "-remove", "--remove", help="To remove an item from the list",
type=int)
parser.add_argument("-l", "-list", "--list", help="displays the tasks or task in the list",
nargs="*")
args = parser.parse_args()
return args
#staticmethod
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def get_todo_list():
database_connection.row_factory = dict_factory
cursor = database_connection.cursor()
cursor.execute("select rowid, * FROM todo_list")
return cursor.fetchall()
def add_to_todo_list(num,task):
cursor = database_connection.cursor()
cursor.execute("INSERT INTO todo_list VALUES (?)", (str(task),))
database_connection.commit()
def remove_from_todo_list(rowid):
cursor = database_connection.cursor()
cursor.execute("DELETE FROM todo_list WHERE rowid = ?", (rowid,))
database_connection.commit()
if __name__ == '__main__':
commands = parse_args()
# Creating table for database using sqlite
database_connection = sqlite3.connect('todo_list.db')
cursor = database_connection.cursor()
cursor.execute('''CREATE TABLE if not exists todo_list(
description TEXT);''')
database_connection.commit()
if commands.add:
# Stops accepting tasks when there is a blank task as input.
if not commands.add == ' ':
add_to_todo_list(commands.add)
elif commands.remove:
remove_from_todo_list(commands.remove)
elif commands.list:
get_todo_list()
However, my database is not accepting any values when I am trying to store data. By putting Id as Id INTEGER PRIMARY KEY when creating the table i.e.
cursor.execute('''CREATE TABLE if not exists todo_list(
Id INTEGER PRIMARY KEY
description TEXT);''')
Will the Id increment as I add data to the database?
sqlite3.InterfaceError: Error binding parameter 1 - probably unsupported type.
Your inputs from argparse are coming in as str, yet you defined your column ID as an INTEGER in your db. Fix is:
cursor.execute("INSERT INTO todo_list VALUES (?,?)", (int(num), task,))
Storing the task(s) in the database which will automatically add an incrementing ID to it.
According to the sqlite docs here, defining a INTEGER PRIMARYKEY will auto-increment. Simply pass a null value to it, and sqlite takes care of the rest for you.
You have a few issues on your code when it comes to displaying and adding the tasks. First, initializing the DB:
cursor.execute(
"""CREATE TABLE if not exists todo_list(
id INTEGER PRIMARY KEY,
description TEXT);"""
)
How you had it before your post edit was fine. Then, the add_to_todo_list:
def add_to_todo_list(task):
cursor = database_connection.cursor()
cursor.execute("INSERT INTO todo_list VALUES (?,?)", (None, str(task)))
database_connection.commit()
Notice the removal of num from the functions input, and the passing of None for the column ID. Within the get_todo_list() you can fetch it more easily as so:
def get_todo_list():
cursor = database_connection.cursor()
cursor.execute("select * FROM todo_list")
return cursor.fetchall()
A fix is also needed in the way you parse your args; for commands.list you need to do the following:
elif commands.list is not None:
print(get_todo_list())
This is since commands.list will be a [] when you do app.py -list, which Python evaluates to False (empty lists are falsey). You also ought to print the contents of the function to terminal -- so don't forget that. With the edits above I can do on my terminal:
python test.py -add Random Task!
python test.py -add Hello World!
python test.py -list
[(1, "['Random', 'Task!']"), (2, "['Hello', 'World!']")]
I am using python 2.7 with pyqt4.10 and sqlite3 Db, trying to get the user input from QlineEdit to insert into sqlite3 table that is already created
Table structure
CREATE TABLE `categories` (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
`category_name` TEXT NOT NULL UNIQUE
);
And am trying to refresh the list in a Qlistwidget with the new data after adding the input
Here is my full code :
def proc():
input_user = self.lineEdit.text()
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("INSERT INTO categories (category_name) VALUES (?)", (input_user, ))
conn.commit()
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("SELECT category_name FROM categories")
category_all = c.fetchall()
for items in category_all:
self.listWidget.addItem(items)
conn.close()
As you see i used input_user = self.lineEdit.text() to get the user input from the QlineEdit
The error is :
Traceback (most recent call last):
File "C:\python\townoftechwarehouse\add_category.py", line 63, in proc
c.execute("INSERT INTO categories (category_name) VALUES (?)", (input_user, ))
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
Found out that the problem was that am using Arabic characters which is not readable for qslite3 so I have to use unicode, here is the edit:
Changed :
input_user = self.lineEdit.text()
To :
input_user1 = self.lineEdit.text()
input_user = unicode(input_user1)
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)
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.