Python SQLite3, table not showing updates - python

I am trying to create a database with SQLite3 in Python.
Creating a table appears to work, but whenever I try to insert data, it doesn't seem to add anything to the database as fetchall() returns nothing, However, if I try to create the ID again, it complains about
unique constraint failed.
Initialization:
import sqlite3
conn = sqlite3.connect('login.db')
c = conn.cursor()
Table Creation:
c.execute("""CREATE TABLE Login (ID INTEGER PRIMARY KEY,
First TEXT NOT NULL,
Last TEXT NOT NULL,
Middle TEXT NOT NULL,
Gender TEXT NOT NULL);""")
conn.commit()
Data Insert:
c.execute("""INSERT INTO Login VALUES (6, 'First', 'Last', 'Hello', 'Male');""")
conn.commit()
Fetching Tables:
print(c.fetchall())
c.close()
conn.close()
When dropping the table into an online reader, it also appears empty.
EDIT:
This is what is shown in the db reader, and in google sheets,
large list of blanks / ";" then this

c.fetchall() would return all of the rows from a SELECT query, which you aren't doing.
import sqlite3
conn = sqlite3.connect('login.db')
c = conn.cursor()
c.execute("""CREATE TABLE Login (ID INTEGER PRIMARY KEY, First TEXT NOT NULL, Last TEXT NOT NULL, Middle TEXT NOT NULL, Gender TEXT NOT NULL);""")
conn.commit()
c.execute("""INSERT INTO Login VALUES (6, 'First', 'Last', 'Hello', 'Male');""")
conn.commit()
c.execute("SELECT * FROM login")
print(c.fetchall())
will happily print
[(6, 'First', 'Last', 'Hello', 'Male')]
As an aside, your code is vulnerable to SQL injection attacks, and you should do
import sqlite3
conn = sqlite3.connect("login.db")
c = conn.cursor()
c.execute(
"""CREATE TABLE Login (ID INTEGER PRIMARY KEY, First TEXT NOT NULL, Last TEXT NOT NULL, Middle TEXT NOT NULL, Gender TEXT NOT NULL);"""
)
conn.commit()
c.execute(
"INSERT INTO Login (ID, First, Last, Middle, Gender) VALUES (?,?,?,?,?)",
(6, "First", "Last", "Hello", "Male"),
)
conn.commit()
c.execute("SELECT * FROM login")
print(c.fetchall())

Related

Auto Incrementing Primary Key Using Entry Widgets into Table

I'm using entries to insert data points into a table where the 'ID' is auto-incrementing. I'm encountering an issue I had when I was working on importing a table with the id being based on auto incrementing, but the solutions I got for that haven't worked with this so far.
import tkinter as tk
import sqlite3
c.execute("""CREATE TABLE IF NOT EXISTS tbl (
id INTEGER PRIMARY KEY NOT NULL,
data text
)""")
def add_equipment():
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("INSERT INTO tbl VALUES(:ID + null, :data)
{"data":data_ent.get()
})
conn.commit()
conn.close()
Doing this gives me an error of did not supply value for binding parameter id, removing the ':id + null' gives me an error of 1 column doens't have a supplied value. I used a for loop on the import version of this, but when I tried to do a loop as:
for row in c.fetchall():
c.execute('variable for the insert command & data', row)
it gives me no error, but doesn't insert the data into the table. I assume the for loop is wrong, but I'm not sure what it should be since this is meant to insert a single record at a time.
def add_equipment():
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("INSERT INTO tbl VALUES(:ID + null, :data)
{"id":'NULL',
"data":data_ent.get()
})
conn.commit()
conn.close()
This gives id a binding parameter and allows the null to auto increment as supposed to.

sqlite3.OperationalError: table responses has 5 columns but 6 values were supplied - tkinter

I have this error with one of my sqlite database tables that I cannot solve, even after looking online for hours. I have also tried deleting the database and starting with a new one but this did not work.
The Error: line 90, in submit1
c.execute("INSERT INTO responses VALUES (:company, :roles, :interview, :offer, :wage_offered, :start_date)",
sqlite3.OperationalError: table responses has 5 columns but 6 values were supplied
However there are 6 columns so I do not understand why this error is cropping up.
the submit1 function Code is posted below:
#create submit function for
def submit1():
# Create a databse or connect to one
connection = sqlite3.connect('jobtracker.db')
#Create a cursor
c = connection.cursor()
# Insert into table
c.execute("INSERT INTO responses VALUES (:company, :roles, :interview, :offer, :wage_offered, :start_date)",
{
'company': company1.get(),
'roles': role1.get(),
'interview': interview.get(),
'offer': offer.get(),
'wage_offered': wage_offered.get(),
'start_date': start_date.get()
})
# Commit changes
connection.commit()
# Close connection
connection.close()
And here is the code for the database:
#Creating database
conn = sqlite3.connect('jobtracker.db')
c = conn.cursor()
#Creating tables for database
c.execute("""CREATE TABLE IF NOT EXISTS applications (
company text,
role text,
industry text,
location text,
wage_min integer,
wage_max integer,
start_date integer,
status text
)""")
c.execute("""CREATE TABLE IF NOT EXISTS responses (
company text,
role text,
interview integer,
offer integer
wage_offered integer,
start_date integer
)""")
conn.commit()
conn.close()
#create submit function for
def submit():
# Create a databse or connect to one
connection = sqlite3.connect('jobtracker.db')
#Create a cursor
c = connection.cursor()
# Insert into table
c.execute("INSERT INTO applications VALUES (:company, :roles, :industry, :location, :wage_min, :wage_max, :start_date, :status)",
{
'company': company.get(),
'roles': role.get(),
'industry': industry.get(),
'location': location.get(),
'wage_min': wage_min.get(),
'wage_max': wage_max.get(),
'start_date': start_date.get(),
'status': status.get()
})
# Commit changes
connection.commit()
# Close connection
connection.close()
Thank you in advance.
I think the table has only 5 fields
You are trying to insert 6 fields

SQLite3 primary key not auto incrementing

I tried writing this code hoping that it will auto increment, but somehow it is not working and the output entries in id column are set to 'None'.I have also tried other answers but none of them are working.Please help if possible.
Here is the code:
import sqlite3
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY,title text,author text,year int,isbn int)")
conn.commit()
conn.close()
def insert(title,author,year,isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("INSERT INTO book VALUES (?,?,?,?)",(title,author,year,isbn))
conn.commit()
conn.close()
def view():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("SELECT * FROM book ")
rows=cur.fetchall()
conn.close()
return rows
connect()
insert("sample","abc",2003,123456)
insert("sample2","def",2003,123457)
print(view())
This is the output:
[(None, 'sample', 'abc', 2003, 123456), (None, 'sample2', 'def', 2003, 123457)]
Answer Edited: Thanks to Shawn's comment I went back to play with the code and hunt down the problem It is true that AUTOINCREMENT is not needed and as such is not the problem (I learned something new about sqlite).
The following code does work. Notice, since you're not supplying data to all columns in the table that you must specify which columns you are inserting data into in your insert statement. I have removed the unnecessary AUTOINCREMENT, and modified the insert statement to work correctly.
Also note: As others have stated, you should not use * wild card for selecting all columns in production code, but instead list all columns individual.
import sqlite3
def connect():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY,title text,author text,year int,isbn int)")
conn.commit()
conn.close()
def insert(title,author,year,isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("INSERT INTO book (title, author, year, isbn) VALUES (?,?,?,?)",(title,author,year,isbn))
conn.commit()
conn.close()
def view():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("SELECT * FROM book ")
rows=cur.fetchall()
conn.close()
return rows
connect()
insert("sample","abc",2003,123456)
insert("sample2","def",2003,123457)
print(view())
The produced output is:
[(1, 'sample', 'abc', 2003, 123456), (2, 'sample2', 'def', 2003, 123457)]
First SQLite recommends that you not use auto increment as your primary, you should select fields that will define a unique record whenever possible.
Second the data type you are passing in is “int” and requires the autoincrement keyword following primary key.
Third you should avoid using * in your select statement. If you simply need a row number back you can query the fields you need and add in the standard field “rowid”.

Python SQLite3 function not printing any data

I have created a function that is supposed to send all the items, with a stock level of less than 10, in my database to a text file. But i am not receiving any data when I press the reorder button.
def Database():
global conn, cursor
conn = sqlite3.connect("main_storage.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS `admin` (admin_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT, password TEXT)")
cursor.execute("CREATE TABLE IF NOT EXISTS `product` (product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, product_name TEXT, product_qty TEXT, product_price TEXT)")
cursor.execute("CREATE TABLE IF NOT EXISTS `basket` (product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, product_name TEXT, product_qty TEXT, product_price TEXT)")
cursor.execute("SELECT * FROM `admin` WHERE `username` = 'admin' AND `password` = 'admin'")
if cursor.fetchone() is None:
cursor.execute("INSERT INTO `admin` (username, password) VALUES('admin', 'admin')")
conn.commit()
def reorder():
global items
Database()
cursor.execute("SELECT `product_name` FROM `product` WHERE `product_qty` <= 10")
items = cursor.fetchall()
print(items)
cursor.close()
conn.close()
I expect the output to be an array of items within my database e.g. [44, 'motherboard', 9, 80] where 44 is product_id, motherboard is product_name, 9 is product_stock and 80 is product_price. I am actually getting an array with nothing in like: []
product_qty is defined as a TEXT column, so comparisons like <= will be performed between the string values of operands. This may not give the results that you expect:
>>> '8' < '10'
False
Recreate your tables with INTEGER or REAL as the column type for numeric values to get the behaviour that you want. For example:
cursor.execute("""CREATE TABLE IF NOT EXISTS `product` """
"""(product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"""
"""product_name TEXT, product_qty INTEGER, product_price REAL)""")

Creating database in Python using sqlite3

I got stuck when I was trying to create database in Python using sqlite3. The below is what I did. When I tried to run, it kept telling me the tables already exist. I couldn't figure out why. Thanks!
import sqlite3
variables = (data)
functions = (data)
var_func = (data)
conn = sqlite3.connect('python_database')
c = conn.cursor()
#create table
c.execute(''' CREATE table variable_table (
id integer,
name text,
module text,
type text,
desc text) ''')
c.execute(''' CREATE table function_table (
id integer,
name text) ''')
c.execute(''' CREATE table var_func_table (
variable_id integer,
function_id integer,
type text) ''')
#fill tables with data
for row in variables:
c.execute ('insert into variable_table values (?,?,?,?,?)', row )
for row in functions:
c.execute ('insert into function_table values (?,?)', row)
for row in var_func:
c.execute ('insert into var_func_table values (?,?,?)', row)
# Save (commit) the change
conn.commit
conn.close

Categories

Resources