Copy data from one table to another sqlite3 - python

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

Related

"Incorrect number of bindings supplied" errors

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

Error: table book has 4 columns but 5 values were supplied

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

Python - Export MySQL select query results to CSV

Im trying to export MySQL select query results to CSV file.
Im using lambda for this, and my database is in RDS.
I can able to connect and run the queries.
But when I try to save the select query results in CSV format, its not working.
Need python developers help to write this script.
Note: Unicodewritter will not work on lambda.
Lambda function:
import sys
import logging
import rds_config
import pymysql
#rds settings
rds_host = "connection_link"
name = rds_config.db_username
password = rds_config.db_password
db_name = rds_config.db_name
logger = logging.getLogger()
logger.setLevel(logging.INFO)
try:
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
except:
logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
sys.exit()
logger.info("SUCCESS: Connection to RDS mysql instance succeeded")
def handler(event, context):
"""
This function fetches content from mysql RDS instance
"""
item_count = 0
with conn.cursor() as cur:
cur.execute("create table Employee3 ( EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))")
cur.execute('insert into Employee3 (EmpID, Name) values(1, "Joe")')
cur.execute('insert into Employee3 (EmpID, Name) values(2, "Bob")')
cur.execute('insert into Employee3 (EmpID, Name) values(3, "Mary")')
conn.commit()
cur.execute("select * from Employee3")
for row in cur:
item_count += 1
logger.info(row)
#print(row)
The below standard method should work to write all rows :
with conn.cursor() as cur:
cur.execute("create table Employee3 ( EmpID int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))")
cur.execute('insert into Employee3 (EmpID, Name) values(1, "Joe")')
cur.execute('insert into Employee3 (EmpID, Name) values(2, "Bob")')
cur.execute('insert into Employee3 (EmpID, Name) values(3, "Mary")')
conn.commit()
cur.execute("select * from Employee3")
res = cur.fetchall()
with open('output.csv','w') as fileout:
writer = csv.writer(fileout)
writer.writerows(res)
If you need to process lines row by row, you can use the writerow instead :
cur.execute("select * from Employee3")
with open('output.csv','w') as fileout:
writer = csv.writer(fileout)
for row in cur:
writer.writerow(row)

Sqlite dynamic column names

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

Why doesn't Python sqlite3 insert auto-incremented ID

In Python 3.4.1, why doesn't sqlite3 insert the auto-incremented ID into the table in the below program? According to the SQLite documentation, an integer primary key column should auto-increment, and I can see that from cur.lastrowid returning a valid integer, BUT the same value is not inserted into the table (it becomes NULL instead).
import sqlite3
with sqlite3.connect(':memory:') as conn:
cur = conn.cursor()
# Note that column 'id' is an integer primary key
cur.execute('create table test (id int primary key , name text)')
cur.execute('insert into test (name) values (?)', ('Test',))
last_id = cur.lastrowid
assert last_id is not None
id_, = cur.execute('select id from test').fetchone()
assert id_ == last_id, '{} != {}'.format(id_, last_id)
Apparently, I was mistaken in thinking that 'int' is a synonym for 'integer' in SQLite. In fact, columns are typeless in SQLite and integer primary key is an exception to this rule, declaring effectively an auto-incremented column:
import sqlite3
with sqlite3.connect(':memory:') as conn:
cur = conn.cursor()
# Note that column 'id' is an integer primary key
cur.execute('create table test (id integer primary key , name text)')
cur.execute('insert into test (name) values (?)', ('Test',))
last_id = cur.lastrowid
assert last_id is not None
id_, = cur.execute('select id from test').fetchone()
assert id_ == last_id, '{} != {}'.format(id_, last_id)

Categories