SQLite3 primary key not auto incrementing - python

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

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.

Create multiple table with python in Sqlite

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.

Insert Python string or dictionary into MySQL

I have a Python string (or potentially a Python dictionary) that I'd like to insert to MySql table.
My String is the following:
{'ticker': 'BTC', 'avail_supply': 16479075.0, 'prices': 2750.99, 'name': 'Bitcoin', '24hvol': 678995000.0}
I have the same kind of error if I want to insert the Dict format.
I really don't understand this kind of error (i.e. the '\' in-between the components of the string).
How can I deal with this error? Any why to properly insert a whole string to a particular TEXT cell in SQL?
Many thanks !!
Here is how to connect, make a table, and insert in the table.
import MySQLdb as mdb
import sys
#connect
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
#need the cursor object so you can pass sql commands, also there is a dictionary cursor
cur = con.cursor()
#create example table
cur.execute("CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
#insert what you want
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
Example above will make a table with 2 cols, one ID and one name
look here on an example on how to insert stuff from dictionary with keys and list as value to sql, basically you need place holders
sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);"
data = {'qwe':1, 'asd':2, 'zxc':None}
conn = MySQLdb.connect(**params)
cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()
conn.close()
or you can go with this as an example for a simple straight forward dict
placeholders = ', '.join(['%s'] * len(myDict))
columns = ', '.join(myDict.keys())
sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, columns, placeholders)
cursor.execute(sql, myDict.values())

Python psycopg2 syntax error

I am new to python and working on using the psycopg2 to insert data in postgres database. I am trying to insert items but get the error message
"Psycopg2.ProgrammingError: syntax error at or near "cup"
LINE 1: INSERT INTO store VALUES(7,10.5,coffee cup)
with the ^ next to coffee cup. I am assuming the order is wrong but i thought you could enter it this way as long as you specified the values.
Here is the code.
import psycopg2
def create_table():
conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert(quantity, price, item):
conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
cur=conn.cursor()
cur.execute("INSERT INTO store VALUES(%s,%s,%s)" % (quantity, price, item))
conn.commit()
conn.close()
create_table()
insert(7, 10.5, 'coffee cup')
Remember to always use the second argument of the execute command to pass the variables, as stated here.
Also, use the name of the fields in your syntax:
cur.execute("INSERT INTO store (item, quantity, price) VALUES (%s, %s, %s);", (item, quantity, price))
That should do the trick.
Problem in your case is coffee cup parameter value is considered as string but psycopg2 accept the value in single quote.
Basically as per my understanding when we create SQL query for psycopg2 it ask for single quote for data parameters [if you have given double quote for query start and end]
In your case you have given double quote for Query Start and end so you need to give single quote for the parameters.
My Observation is you provide single quote for each data paramater in psycopg2
import psycopg2
def create_table():
conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price REAL)")
conn.commit()
conn.close()
def insert(quantity, price, item):
conn=psycopg2.connect("dbname='db1' user='postgres' password='postgress123' host='localhost' port='5432'")
cur=conn.cursor()
#cur.execute("INSERT INTO store VALUES(%s,%s,%s)" % (quantity, price, item))
cur.execute("INSERT INTO store VALUES('%s','%s','%s')" % (quantity, price, item))
conn.commit()
conn.close()
create_table()
insert(7, 10.5, 'coffee cup')
I also faced the very same problem, and after a while troubleshooting the code, I found that I forgot to add commas(,) in the Insert query.
The code that causes the error:
data['query'] = 'insert into contacts (name, contact_no, alternate_contact_no, email_id, address)' \
'values (%s %s %s %s %s)'
As you can see in above code, I forgot to add commas after every '%s'.
The correct code:
data['query'] = 'insert into contacts (name, contact_no, alternate_contact_no, email_id, address)' \
'values (%s, %s, %s, %s, %s)'
Hope, It helps!

Update Table with a valuable ( Sqlite)

i can't insert or update with a valuable.
i don't know syntax
self.Value = self.Pass.text()
Database.ram.execute('''INSERT INTO Pass VALUE (?)''',self.Value)
thanks
There is not much of your code to go on but I would use the following SQLite statement:
Database.ram.execute('UPDATE table SET column = ?', (self.Value))
conn.commit() # with conn = sqlite3.connect('db name')
And if you want to insert:
Database.ram.execute('INSERT INTO table (column) VALUES(?)', (self.Value))
conn.commit() # with conn = sqlite3.connect('db name')

Categories

Resources