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)
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 have a SQLite table that I wanted to update. This table ('abc') already has a row inserted through some other process for id and useremail. Now, I want my query to lookup this record based on where condition (on useremail) and update the value of column logintime. I am pretty new to Sqlite so need some help in figuring it out. Code below -
creating a new table (works OK)
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS abc (
id INTEGER PRIMARY KEY,
useremail TEXT,
logintime TEXT,
logouttime TEXT
);
""")
conn.commit()
conn.close()
code for inserting a record (works OK)
email = ['jojo#jojo.com']
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
c.execute('insert into abc (useremail) values(?)', email)
code for updating column logintime where value in column useremail = email:
conn = sql.connect('/content/sample_data/userlogs.db')
c = conn.cursor()
now = datetime.now()
c.execute('UPDATE abc SET logintime = ? WHERE useremail = ?', (now, email))
I am having trouble with this c.execute statement.
I am trying to pull data the CDC and put the data into a database. My most recent traceback is: sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type. And do not know what that means or how to fix my code. Any help will be greatly appreciated.
Here is my code:
import json
from urllib.request import urlopen
import ssl
import sqlite3
conn=sqlite3.connect('cdcdata.sqlite')
cur=conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS CState (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
state_id INTEGER, State TEXT, Count INTEGER)''')
cur.execute('''CREATE TABLE IF NOT EXISTS CDate(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
date_id INTEGER, state_id INTEGER, Date INTEGER, Count INTEGER)''')
cur.execute('''CREATE TABLE State_COIVD_Numbers (State TEXT, state_id INTEGER, date_id INTEGER, count INTEGER)''')
#
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
data = open('rows.json', encoding='utf8').read()
info = json.loads(data)
for data in info['meta']['view']['columns']:
data1 = data['position']
if data1 != 1:
continue
date_data = data['cachedContents']['top']
cur.execute("SELECT Date FROM CDate WHERE Count= ?", (date_data,))
cur.fectone()
#print(date_data)
for data in info['meta']['view']['columns']:
data1 = data['position']
if data1 != 2:
continue
state_data = data['cachedContents']['top']
cur.execute("SELECT State FROM CState WHERE Count= ?", (state_data,))
cur.fetchone()
# print(state_data)
cur.execute('''INSERT INTO CState(State, Count) VALUES(?,?)''',(state_data,))
cur.execute('''INSERT INTO CDate(Date, Count) VALUES(?,?)''', (date_data,))
cur.execute('''select CState.State, CDate.Date FROM CState join CDate on State_COVID_Numbers.state_id=state.id''' )
cur.execute('''select CDate.Date, CState.State FROM CDate join CState on State_COVID_Numbers.date_id=date.id''' )
conn.commit()
conn.close()
Print('You Did It!')
I am new to coding and I have tried many things, but I do not know what to try to solve this problem.
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()