Create multiple table with python in Sqlite - python

I've search trought a lot a internet site and I cannot find the answer.
I try to create 4 tables in my SQLite database with this code:
try:
conn = sqlite3.connect(os.path.join(current_directory, 'fidouda.db'))
c = conn.cursor()
c.execute('''CREATE TABLE Clients (ID INTEGER PRIMARY KEY AUTOINCREMENT, Prenom, Nom, Adresse, Email, Telephone, Genre, Factures, Fidelite);''')
c.execute('''CREATE TABLE Factures (ID, Client, Items, Date, Prix, Promotion, Sous-total, Total, Payer, Rpayer);''')
c.execute('''CREATE TABLE Inventaire (Stock, Nom, Prix);''')
c.execute('''CREATE TABLE Rabais (Nom, Pourcentage);''')
except Error as e:
print(e)
finally:
if conn:
conn.close()
return os.path.join(current_directory, fname)
The problem is that only the first table are created. How can I create all my table ?

If you run this code, it will output this error:
sqlite3.OperationalError: near "-": syntax error
Specifically, the hyphen in the column Sous-total, you can either surround the column name in quotes, like this:
c.execute('''CREATE TABLE Factures (ID, Client, Items, Date, Prix, Promotion, 'Sous-total', Total, Payer, Rpayer);''')
Or pick another column name that won't cause problems.

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

Python insert to MySQL : Failed to record Price 1452 (23000): Cannot add or update a child row: a foreign key constraint fails

I have a python code that insert variables "link" and "name" into one table "pricedb" and "avgrate" into the other table
#insert product into product table
def insertProduct(link, name):
try:
#mySQL instruction to insert to link and name column
mySqlInsertProduct = """INSERT INTO products_list (link, name) VALUES (%s, %s) """
recordProduct = (link, name)
#executes the instruction and commit
cursor.execute(mySqlInsertProduct, recordProduct)
connection.commit()
print("Product Record inserted, ID:", cursor.lastrowid)
except mysql.connector.Error as error:
print("Failed to record Product {}".format(error))
def insertPrice(pricedb, avgrate): #DOESNT WORK
try:
mySqlInsertPrice = """INSERT INTO scan_history (price, ratings) VALUES (%s, %s) """
recordPrice = (pricedb, avgrate)
cursor.execute(mySqlInsertPrice, recordPrice)
connection.commit()
print("Current Price recorded")
except mysql.connector.Error as error:
print("Failed to record Price {}".format(error))
#executes the insert functions
insertProduct(link_shrt, product_name)
insertPrice(price_final, ratings)
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
It can successfully do insertProduct but fails at insertPrice
Failed to record Price 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`bp40_scraperDB`.`scan_history`, CONSTRAINT `scan_history_ibfk_1` FOREIGN KEY (`prod_IDfk`) REFERENCES `products_list` (`prod_IDpk`) ON UPDATE NO ACTION)
I've tried resetting the AUTO_INCREMENT to begin at 1 and emptied both tables.
The insertProduct ran first and put prod_ID 1 in the primary key already, so I don't know what's wrong with it
Here are my tables
name and link indexes are just UNIQUE
this is the table with foreign key
The primary key prod_IDpk in the product table also needs to be referenced as the foreign key prod_IDfk in the price table scan_history otherwise the price doesn't know what it is linking to.
You are getting back the product id at the line
print("Product Record inserted, ID:", cursor.lastrowid)
prod_ID = cursor.lastrowid
Now pass that to the price insert to make the link
mySqlInsertPrice = """INSERT INTO scan_history (prod_IDfk, price, ratings) VALUES (%s, %s) """
recordPrice = (prod_ID, pricedb, avgrate)

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”.

MYSQL and python error

I want to insert data in MYSQL database using python
here my code
import MySQLdb
#connect to db
db= MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="new_schema")
#setup cursor
cursor = db.cursor()
#create anooog1 table
cursor.execute("DROP TABLE IF EXISTS try")
sql = """CREATE TABLE try (
COL1 INT, COL2 INT )"""
cursor.execute(sql)
#insert to table
cursor.execute("""INSERT INTO try VALUES (%s,%s)""",(188,90))
db.commit()
db.rollback()
#show table
cursor.execute("""SELECT * FROM try""")
print cursor.fetchall()
db.close()
but the error is in my sql
Error: `new_schema`.`try`: table data is not editable because there is no primary key defined for the table ...
What shall I do?
Your error is because you've created a table with no primary key.
Use this statement (or similar):
sql = """CREATE TABLE try (COL1 INT, COL2 INT, PRIMARY KEY (COL1))"""
Here we specify that COL1 is to be the primary key for the table. Modify as you need to suit your requirements.
If you wanted to add a string column (with length 128) to your table:
CREATE TABLE try (COL1 INT, COL2 INT, MyString VARCHAR(128), PRIMARY KEY (COL1))

Categories

Resources