Why my code gives error: "sqlite3.OperationalError: no such column: "? - python

Why is my program giving me error indicating that that column does not exist in my Sqlite3 Tasks-table? Here is my code:
class Db:
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
def create_table(self):
create_Tasks_table = '''CREATE TABLE Tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
notes TEXT,
deadline TEXT,
state INTEGER);'''
self.cursor.execute(create_Tasks_table)
self.conn.commit()
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = """INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?), (title, notes, deadline, state)"""
self.cursor.execute(add_to_Tasks_table)
self.conn.commit()
if __name__ == "__main__":
db = Db()
db.create_table()
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
I checked with DB Browser for SQlite that table is created correctly and column name is correct, as indicated on this picture:
EDIT: Here is full error:
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\project\mytest.py", line 91, in <module>
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
File "C:\Users\User\PycharmProjects\project\mytest.py", line 36, in add_task
self.cursor.execute(add_to_Tasks_table)
sqlite3.OperationalError: no such column: title

The problem with your code is that you included the tuple that contains the parameters that you pass inside the sql statement.
It should be placed as the 2nd argument of cursor.execute():
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = "INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?)"
self.cursor.execute(add_to_Tasks_table, (title, notes, deadline, state))
self.conn.commit()

Related

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

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

sqlite3.OperationalError: no such column: circleCat.name

I get the following error when I run my code and I don't know why:
Traceback (most recent call last):
File "python", line 27, in <module>
File "python", line 25, in members_of_circles
sqlite3.OperationalError: no such column: circleCat.name
the code :
import sqlite3
con = sqlite3.connect(":memrory:")
cur = con.cursor()
def creat_tables () :
cur.execute("CREATE table circleCat (id INTEGER PRIMARY KEY, name TEXT,
description TEXT)")
cur.execute("CREATE table members( id INTEGER PRIMARY KEY, name TEXT, level
TEXT, crcl TEXT)")
def add_a_member(name, level, crcl):
cur.execute("INSERT INTO members (name, level, crcl) VALUES (?, ?, ?)" ,
(name, level, crcl));
def add_a_circle(name, description):
cur.execute("INSERT INTO circleCat (name, description) VALUES (?, ?)" ,
(name, description));
creat_tables ()
add_a_circle("Gaming", "for Gaming")
add_a_member("hossam", "beginner", "Gaming")
def members_of_circles():
cur.execute("SELECT name FROM members WHERE members.crcl =
circleCat.name")
members_of_circles()
Your select query is wrong. Try this:
def members_of_circles():
cur.execute("SELECT m.name FROM members m, circleCat c WHERE m.crcl = c.name")

python sqlite3 insert table error: cursor is not connected?

I try to use sqlite3 to import data to a table babyName in my AWS RDS database. For the two methods I tried, the first one data_entry() works fine every time but the second new_data_entry() gave me
Cursor is not connected
or
Not all parameters are used
error. Could you please help me?
import mysql.connector
from mysql.connector import errorcode
# start connection
try:
cnn = mysql.connector.connect(
user = '*****',
password = '*****',
host = '*****-mysql.*****.us-****-1.rds.amazonaws.com',
database = '*******')
print('It works!')
except mysql.connector.Error as e:
if e.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print('Somethign is wrong with username or password')
elif e.errno == errorcode.ER_BAD_DB_ERROR:
print('Database does not exist')
else:
print(e)
# start cursor
import sqlite3
c = cnn.cursor()
def creat_table():
c.execute("CREATE TABLE IF NOT EXISTS babyName (name TEXT, gender TEXT, frequency INTEGER, year TEXT)")
def data_entry():
c.execute("INSERT INTO babyName VALUES ('Mary', 'F', 1234, '2008')")
cnn.commit()
c.close()
cnn.close()
def new_data_entry():
name = 'Wendy'
gender = 'F'
frequency = 321
year = '2006'
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", (name, gender, frequency, year))
cnn.commit()
c.close()
cnn.close()
# creat_table()
data_entry()
print('It works!')
new_data_entry()
The error message I kept getting:
It works!
It works!
Traceback (most recent call last):
File "/Users/*****/sqlite3_python_cc.py", line 53, in <module>
new_data_entry()
File "/Users/*****/sqlite3_python_cc.py", line 45, in new_data_entry
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", values)
File "/Users/*****/anaconda/lib/python3.6/site-packages/mysql/connector/cursor.py", line 529, in execute
raise errors.ProgrammingError("Cursor is not connected")
mysql.connector.errors.ProgrammingError: Cursor is not connected
At the end of data_entry you have closed the connection to the database, cnn, which is saved as a variable in the global scope. When you attempt to run new_data_entry, the connection has already been closed, which is what is give you the error.
Instead, leave the connection open until you are finished.
import sqlite3
c = cnn.cursor()
def creat_table():
c.execute("CREATE TABLE IF NOT EXISTS babyName (name TEXT, gender TEXT, frequency INTEGER, year TEXT)")
def data_entry():
c.execute("INSERT INTO babyName VALUES ('Mary', 'F', 1234, '2008')")
cnn.commit()
def new_data_entry():
name = 'Wendy'
gender = 'F'
frequency = 321
year = '2006'
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (?, ?, ?, ?)", (name, gender, frequency, year))
cnn.commit()
def finish():
c.close()
cnn.close()
data_entry()
print('It works!')
new_data_entry()
finish()
I have the problem solved!
def new_data_entry():
name = 'Wendy'
gender = 'F'
frequency = 321
year = '2006'
c.execute("INSERT INTO babyName (name, gender, frequency, year) VALUES (%s, %s, %s, %s)", (name, gender, frequency, year))
cnn.commit()
def finish():
c.close()
cnn.close()
Change all the "?" to "%s" and the codes all run through~ Thank you guys!

Python's executemany for sqlite3 don't accept list of tuples

I'm trying to create sqlite database from git commits, I have code like this:
if __name__ == '__main__':
path = os.getcwd()
commits = log(path)
if path.endswith("/"):
path = path + "/"
fname = "%sgit.sqlite" % (path)
if os.path.isfile(fname):
os.remove(fname)
con = sqlite3.connect(fname)
con.execute("CREATE TABLE commits (hash VARCHAR(40), author VARCHAR(256), email VARCHAR(256), " +
"message text, date VARCHAR(35))")
cur = con.cursor()
def commit(c):
return (c["hash"], c["author"], c["email"], c["message"], c["date"])
cur.executemany("INSERT INTO commits VALUES(?)", map(commit, commits))
# this prints 2d array
#print json.dumps(map(commit, commits))
# this print tuple
print type(map(commit, commits)[0])
# this print 5
print len(map(commit, commits)[0])
con.close()
the log function return git commits as list of dictionaries, and I've got exception:
Traceback (most recent call last):
File "/home/kuba/bin/gitsql.py", line 48, in <module>
cur.executemany("INSERT INTO commits VALUES(?)", map(commit, commits))
sqlite3.OperationalError: table commits has 5 columns but 1 values were supplied
I'm using Python 2.7.13
you need to specify how many values you want to insert :
cur.executemany("INSERT INTO commits VALUES(?, ?, ?, ?, ?)", map(commit, commits))

Categories