Getting error:
"insert
cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)" ,(title,author,year,isbn))
sqlite3.OperationalError: table book has 4 columns but 5 values were supplied"
while running below code, i want to id column with primary key integer while inserting data in table in database.
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 integer, isbn integer)")
conn.commit()
conn.close()
def insert(title,author,year,isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)" ,(title,author,year,isbn))
conn.commit()
conn.close()
Please help.
why you put NULL in book VALUES (NULL,?,?,?,?) ? try without NULL
cur.execute("INSERT INTO book VALUES (?,?,?,?)" ,(title,author,year,isbn))
Related
Attempting to build a database, inserting from 33 CSV files, my insert statement returns:
ProgrammingError: Incorrect number of bindings supplied. The current statement uses 4, and there are 11 supplied.
I have a CSV file I need to convert a single column from into a string then insert that CSV file into a table. How to do this? I want to create a database I can run queries on after inserting CSV file data into its tables.
import sqlite3
import pandas as pd
from traceback import print_exc as pe
import csv
def Connect():
conn = sqlite3.connect('storefront.db')
curs = conn.cursor()
curs.execute("PRAGMA foreign_keys = ON;") #change back to on after finding errors
return conn, curs
def BuildTables():
conn, curs = Connect()
curs.execute("DROP TABLE IF EXISTS tState;")
curs.execute("DROP TABLE IF EXISTS tZip;")
curs.execute("DROP TABLE IF EXISTS tCust;")
curs.execute("DROP TABLE IF EXISTS tOrder;")
curs.execute("DROP TABLE IF EXISTS tOrderDetail;")
curs.execute("DROP TABLE IF EXISTS tProd;")
sql = """
CREATE TABLE tState(
st TEXT NOT NULL PRIMARY KEY,
state TEXT NOT NULL
);"""
curs.execute(sql)
file = open('data/states.csv')
contents = csv.reader(file)
insert_records = "INSERT INTO tState (st, state) VALUES(?, ?)"
curs.executemany(insert_records, contents)
sql = """
CREATE TABLE tZip(
zip TEXT NOT NULL PRIMARY KEY,
city TEXT NOT NULL,
st TEXT NOT NULL
);"""
curs.execute(sql)
sql = """
CREATE TABLE tCust(
cust_id int AUTO_INCREMENT PRIMARY KEY,
first TEXT NOT NULL,
last TEXT NOT NULL,
addr TEXT NOT NULL,
zip TEXT NOT NULL
);"""
curs.execute(sql)
file3 = open('data/Sales_201901.csv')
cont = csv.reader(file3)
cust = "INSERT INTO tCust (first, last, addr, zip) VALUES(?, ?, ?, ?)"
curs.executemany(cust, cont)
sql = """
CREATE TABLE tOrder(
order_id int AUTO_INCREMENT PRIMARY KEY,
date TEXT NOT NULL
);"""
curs.execute(sql)
order = "INSERT INTO tOrder (date) VALUES(?)"
curs.executemany(order, cont)
sql = """
CREATE TABLE tOrderDetail(
order_id INTEGER NOT NULL REFERENCES tOrder(order_id),
cust_id INTEGER NOT NULL REFERENCES tCust(cust_id),
qty TEXT,
PRIMARY KEY (order_id, cust_id)
);"""
curs.execute(sql)
orderdetails = "INSERT INTO tOrderDetail (qty) VALUES(?)"
curs.executemany(orderdetails, cont)
sql = """
CREATE TABLE tProd(
prod_id INTEGER NOT NULL PRIMARY KEY,
prod_name TEXT NOT NULL,
unit_price TEXT NOT NULL
);"""
curs.execute(sql)
file4 = open('data/prods.csv')
conts = csv.reader(file4)
prod = "INSERT INTO tProd (prod_id, prod_name, unit_price) VALUES (?, ?, ?)"
curs.executemany(prod, conts)
conn.close()
return True
I tried to create table in my database and add PRIMARY KEY to my table by using sqlite3 library, But sqlite3 did not understand NULL
this my 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 integer, isbn integer)")
conn.commit()
conn.close()
def insert(title,author,year,isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title,author,year,isbn))
conn.commit()
conn.close()
view()
def view():
conn=sqlite3.connect('books.db')
cur=conn.cursor()
cur.execute("SELECT \* FROM book")
rows=cur.fetchall()
conn.close()
return rows
connect()
insert('anybook','anyperson',1918,6384515345)
print(view())
I expected the output to be
[(1,'anybook','anyperson',1918,6384515345)]
But it was:
Traceback (most recent call last):
File "e:\CORSES\The Python Mega Course\000. Projects\APPs\4. BookStore\Book Store\BackEnd.py", line 28, in <module>
insert('anybook','anyperson',1918,6384515345)
File "e:\CORSES\The Python Mega Course\000. Projects\APPs\4. BookStore\Book Store\BackEnd.py", line 13, in insert
cur.execute("INSERT INTO book VALUES (NULL,?,?,?,?)",(title,author,year,isbn))
sqlite3.OperationalError: table book has 4 columns but 5 values were supplied
I am working with MySQL but I have some unexpected behaviour.
I have past experience with SQLite but I guess I am missing something here.
Using the query SELECT * FROM tableName I would expect the content of the table to be the output.
Instead I get an int, being the count of rows in the table.
Here is the piece of code I am using.
import MySQLdb
conn=MySQLdb.connect(host="xxx",user="xxx",passwd="xxx")
cursor = conn.cursor()
cursor.execute("create database if not exists Test;")
cursor.execute("use Test;")
cursor.execute("create table if not exists City (id int not null primary key auto_increment, city varchar(50), unique(city));")
cursor.execute("insert into City (city) values ('Firenze');")
cursor.execute("insert into City (city) values ('Roma');")
conn.commit()
print(cursor.execute("select city from City;"))
I would expect to get:
Firenze
Roma
Instead I get:
2
If I run the same query from a SQL client I get the expected output. Any clever idea?
Thanks :)
You are missing the FetchAll() function in your code.
Fetch all is nothing but fetching the data of last executed statement.
import MySQLdb
conn=MySQLdb.connect(host="xxx",user="xxx",passwd="xxx")
cursor = conn.cursor()
cursor.execute("create database if not exists Test;")
cursor.execute("use Test;")
cursor.execute("create table if not exists City (id int not null primary key
auto_increment, city varchar(50), unique(city));")
cursor.execute("insert into City (city) values ('Firenze');")
cursor.execute("insert into City (city) values ('Roma');")
conn.commit()
print(cursor.execute("select city from City;"))
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The thing is print(cursor.execute("select city from City;") returns you the number of rows or rows count.
For the complete records use something like this
myresult = cursor.fetchall()
for x in myresult:
print(x)
So I have a database containing the products I will be holding, within this database I have a basket table where users can add items they would like to buy. For some reason, I am unable to take a selection within the view window and copy that data into my basket table.
Here is the function I have created for moving the data.
def Move():
if not tree.selection():
error = tkMessageBox.showerror("Error", "Cannot move nothing to basket")
else:
result = tkMessageBox.askquestion('CCOS', 'Do you want to add this to the basket?', icon="warning")
if result == 'yes':
curItem = tree.selection()
print(curItem)
contents = (tree.item(curItem))
selecteditem = contents['values']
Database()
cursor.execute("INSERT INTO `basket` (product_name, product_qty, product_price) VALUES(?, ?, ?)",
(str(PRODUCT_NAME.get()), int(PRODUCT_QTY.get()), int(PRODUCT_PRICE.get())))
conn.commit()
PRODUCT_ID.set("")
PRODUCT_NAME.set("")
PRODUCT_PRICE.set("")
PRODUCT_QTY.set("")
cursor.close()
conn.close()
Comment:
I have a range of different functions in my code, Database() is its own function that creates the database and cursor = conn.connect(). I am not getting an error, but when i run the function, no data is copied into the table.
When I call print(curItem), all that is outputted is : ('I002',)
Here is the database function:
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()
I have the following Sqlite setup trying to update Tablename table with Keys items as both column name and value
The problem is that i want to add all items into single record where Name doesn't change but Items change to take all Items in Keys
My code will do this over for loop but with multiple records , All i want is a single records with all Items
Keys=['a','b',etc]
Tablename='Asfoor'
Name='Deek'
for item in keys:
data=[Name,Item]
cur.executemany("INSERT INTO "+Tablename+" (Name,"+Item+") VALUES(?,?)",(data,))
Complete code :
import sqlite3
import sys
tablename='asfoor'
table_data=['Name','a','b','c']
try:
con = sqlite3.connect('dbtrials.db')
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS "+tablename+"")
cur.execute("CREATE TABLE "+tablename+" (ID INTEGER PRIMARY KEY AUTOINCREMENT ,Name TEXT, "+table_data[1]+" TEXT, "+table_data[2]+" TEXT, "+table_data[3]+" TEXT )")
keys=['a','b','c']
name='deek'
for item in keys:
data=[name,item]
cur.executemany("INSERT INTO "+tablename+" (name,"+item+") VALUES(?,?)",(data,))
cursor = cur.execute("select * from "+tablename+" ")
for row in cursor :
print(row)
except sqlite3.Error as e:
print ("Error %s:" % e.args[0])
sys.exit(1)
finally:
if con:
con.close()