sqlite3 dose not understand NULL to create primary key column in table - python

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

Related

make temporary database with sqlite

I wanna make a temporary database but I don't know I going in the right way or not
I get the error no such table: list but I don't know why python raise that error
this is my code:
def connect():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS list (id INTEGER PRIMARY KEY , namee VARCHAR , number INTEGER ,"
" price INTEGER )"
)
conn.commit()
conn.close()
def insert(name, number, price):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"INSERT INTO list VALUES (NULL ,?,?,?,?,?)", (name, number, price)
)
conn.commit()
conn.close()
def view():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"SELECT * FROM list"
)
rows = cur.fetchall()
conn.close()
return rows
def delete(id):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("DELETE FROM list WHERE id=?", (id,))
conn.commit()
conn.close()
connect()
and this is my error:
Traceback (most recent call last):
File "D:\python\WindowsProject\app\user\memory.py", line 42, in <module>
print(insert('pizza',2,6))
File "D:\python\WindowsProject\app\user\memory.py", line 17, in insert
cur.execute(
sqlite3.OperationalError: no such table: list
sqlite3.connect(":memory:") creates an in-memory database that only exists as long as the connection is in use.
The problem is that you're closing the database connection in each function. As soon as you close it, the in-memory database vanishes. INSERT fails because the table no longer exists.
You'll need to preserve (or pass) the conn and cur objects so that you can use them between functions.

why table is not creating by this script?

I am creating a test script to create database and insert data.
database is created but no table is creating.
here is code.
import sqlite3
def connect() :
conn=sqlite3.connect("fullsta.db" )
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS post(id INTEGER PRIMARY KEY,title text,content text,date text,author text)")
conn.commit()
conn.close()
def insert(title,content,date,author):
conn=sqlite3.connect("fullsta.db" )
cur=conn.cursor()
cur.execute("INSERT INTO post VALUES (NULL,title ,content ,date,author )")
conn.commit()
conn.close()
insert("hello","hello","hello","hello")
here is the error.
PS C:\Users\Anil Kumar\Desktop\project\my site\web_blog> py test.py
Traceback (most recent call last):
File "test.py", line 17, in <module>
insert("hello","hello","hello","hello")
File "test.py", line 13, in insert
cur.execute("INSERT INTO post VALUES (NULL,title ,content ,date,author )")
sqlite3.OperationalError: no such table: post
Your code does not have connect function called.
but you need more clearer code to see what is happening.
maybe this will handle what you want to do
import sqlite3
class DB:
cursor = None
connection = None
def __init__(self, db):
connection = sqlite3.connect(db)
self.cursor = connection.cursor()
self.connection = connection
def migrate(self):
q = "CREATE TABLE IF NOT EXISTS post(id INTEGER PRIMARY KEY,title text,content text,date text,author text)"
self.cursor.execute(q)
def exec(self, sql, variables=None):
if variables:
return self.cursor.execute(sql, variables).fetchall()
return self.cursor.execute(sql).fetchall()
def commit(self):
self.connection.commit()
def close(self):
self.connection.close()
def force_exit(self):
self.commit()
self.close()
def insert(title, content, date, author):
cur = DB("fullsta.db")
cur.migrate()
cur.exec("INSERT INTO post VALUES (NULL, ?, ?, ?, ? )", (title, content, date, author))
cur.force_exit()
insert("hello", "hello", "hello", "hello")

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

Get API-endpoint and store it in a SQLite (Python)

As you can see I am trying to fetch data from this API-endpoint https://api.coindesk.com/v1/bpi/currentprice.json and I have chosen few data I want to fetch and store it in SQLite.
When I try to save it in a database it gives me this error:
Traceback (most recent call last):
File "bitcoin.py", line 41, in <module>
cur.execute("INSERT INTO COINS (Identifier, symbol, description) VALUES (?, ?, ?);", to_db)
sqlite3.ProgrammingError: Binding 1 has no name, but you supplied a dictionary (which has only names).
How can I store the some of the data from API-endpoint into the database?
I'm doing this to learn programming and still new to this so hopefully, you can guide me in the right way.
Here is what I have tried so far:
import requests
import sqlite3
con = sqlite3.connect("COINS.db")
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS COINS')
cur.execute(
"CREATE TABLE COINS (Identifier INTEGER PRIMARY KEY, symbol TEXT, description TEXT);"
)
r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
to_db = r.json() # I do not have to do it in json, CSV would also be another
# solution but the data that is been stored cannot be static.
# It has to automatically fetch the data from API-endpoint
cur.execute("INSERT INTO COINS (Identifier, symbol, description) VALUES (?, ?, ?);", to_db)
con.commit()
con.close()
import requests
import sqlite3
con = sqlite3.connect("COINS.db")
cur = con.cursor()
cur.execute('DROP TABLE IF EXISTS COINS')
cur.execute(
"CREATE TABLE COINS (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENTUNIQUE,
symbol TEXT, description TEXT);")
r = requests.get('https://api.coindesk.com/v1/bpi/currentprice.json')
to_db = r.json()
des=to_db['bpi']['USD']['description']
code=to_db['bpi']['USD']['code']
cur.execute("INSERT INTO COINS (symbol, description) VALUES (?, ?);",
(des,code))
con.commit()
con.close()
Check full code

Using SQLite3 in Python

I am trying to store some parsed feed contents values in Sqlite database table in python.But facing error.Could anybody help me out of this issue.Infact it is so trivial question to ask!I am newbie!..Anyway thanks in advance!
from sqlite3 import *
import feedparser
data = feedparser.parse("some url")
conn = connect('location.db')
curs = conn.cursor()
curs.execute('''create table location_tr
(id integer primary key, title text ,
updated text)''')
for i in range(len(data['entries'])):
curs.execute("insert into location_tr values\
(NULL, data.entries[i].title,data.feed.updated)")
conn.commit()
curs.execute("select * from location_tr")
for row in curs:
print row
And Error is:
Traceback (most recent call last):
File "F:\JavaWorkspace\Test\src\sqlite_example.py", line 16, in <module>
(NULL, data.entries[i].title,data.feed.updated)")
sqlite3.OperationalError: near "[i]": syntax error
Try
curs.execute("insert into location_tr values\
(NULL, '%s', '%s')" % (data.entries[i].title, data.feed.updated))
the error should be this line
curs.execute("insert into location_tr values\
(NULL, data.entries[i].title,data.feed.updated)")
data.entries[i].title comes from Python. So if you enclose it in double quotes, it becomes a literal string, not a value. It should be something like this:
curs.execute("insert into location_tr values (NULL," + data.entries[i].title +","+data.feed.updated+")")

Categories