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!
Related
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()
When I executing the following function, I get the following response:
Failed to insert data into sqlite table: no such table: users
user_id = uuid.uuid4()
save_record.name = name
save_record.score = score
last_time = datetime.now()
try:
conn = sqlite3.connect('OnlineJeopardy.db')
cursor = conn.cursor()
print("Successfully Connected to OnlineJeopardy DB.")
sqlite_insert_query = """INSERT INTO users
(User_id, Name, Score, Last_time)
VALUES
(?, ?, ?, ?)"""
add_to_db = cursor.execute(sqlite_insert_query, (user_id, name, score, last_time))
conn.commit()
cursor.close()
except sqlite3.Error as error:
print("Failed to insert data into sqlite table: ", error)
finally:
if (conn):
conn.close()
print("The SQLite connection is closed")
When I execute this query in DB Browser, with actual values instead of placeholders, it all goes well.
I've tried swapping placeholders to actual values (as below) within the query in sqlite3 but the outcome was the same.
conn = sqlite3.connect('OnlineJeopardy.db')
cursor = conn.cursor()
print("Successfully Connected to OnlineJeopardy DB.")
sqlite_insert_query = """INSERT INTO users
(User_id, Name, Score, Last_time)
VALUES
('ID-1337', 'Adam', 20, '2020-06-12 23:18:58')"""
add_to_db = cursor.execute(sqlite_insert_query)
conn.commit()
cursor.close()
I'm writing a program to store credit card values as practice.
I keep getting the error "sqlite3.OperationalError: no such column:
the table is created and the column: name.
the column name exists in in the cards table in cc.db in SQLiteStudio
any help appreciated.
import sqlite3
conn = sqlite3.connect('cc.db')
c = conn.cursor()
def createTABLE():
c.execute("""CREATE TABLE IF NOT EXISTS cards (
name text,
ccnumber integer,
exp_date text,
csv integer
)""")
conn.commit()
print('table created')
def entercard():
ccname = input('Enter the name of the new card: ')
ccnumber = input('Enter the card number: ')
ccexp_date = input('Enter the Expiration date: ')
cccsv = input('Enter the CSV number from the back of the card: ')
c.execute("INSERT INTO cards VALUES (?, ?, ?, ?),(name, ccnumber, exp_date, csv)");
conn.commit()
def printall():
for card in c.execute('SELECT * FROM cards'):
print(card)
createTABLE()
entercard()
printall()
conn.close()
I cannot determine why you're getting that particular error, but you have a problem with the following line:
c.execute("INSERT INTO cards VALUES (?, ?, ?, ?),(name, ccnumber, exp_date, csv)");
It is all a string. You need instead to separate the variables from the query string like so:
c.execute("INSERT INTO cards VALUES (?, ?, ?, ?)",(name, ccnumber, exp_date, csv))
I did the bellow in order to store values and retrieve them from the table.
You need to make the line look more like this.
c.execute("INSERT INTO cards(name,ccnumber,exp_date,csv) VALUES ('Tom','new1','new2','new3');")
Space
import sqlite3
conn = sqlite3.connect('cc.db')
c = conn.cursor()
def createTABLE():
c.execute("""CREATE TABLE IF NOT EXISTS cards (
name text,
ccnumber integer,
exp_date text,
csv integer)""")
conn.commit()
c.execute("INSERT INTO cards(name) VALUES ('Tom');")
conn.commit()
p=c.execute('SELECT * FROM cards')
j= p.fetchall()
print(j)
for i in j:
print(i)
print(p)
print('table created')
def entercard():
ccname = input('Enter the name of the new card: ')
c.execute("INSERT INTO cards(name) VALUES ('"+ccname+"')")
conn.commit()
def printall():
for card in c.execute('SELECT * FROM cards'):
print(card)
createTABLE()
entercard()
printall()
conn.close()
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")
I need to update a row if a record already exists or create a new one if it dosen't. I undersant ON DUPLICATE KEY will accomplish this using MYSQLdb, however I'm having trouble getting it working. My code is below
cursor = database.cursor()
cursor.execute("INSERT INTO userfan (user_id, number, round VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE user_id =%s, number=%s, round=%s", (user_id, number, round))
database.commit()
primary key is user_id
A parenthesis was missiing. You can also use the VALUES(column) in the ON DUPLICATE KEY UPDATE section of the statement:
cursor = database.cursor()
cursor.execute("""
INSERT INTO userfan
(user_id, number, round)
VALUES
(%s, %s, %s)
ON DUPLICATE KEY UPDATE
-- no need to update the PK
number = VALUES(number),
round = VALUES(round) ;
""", (user_id, number, round) # python variables
)
database.commit()
def insertAndUpdateData(lVideoList, no_of_gate):
connection = sqlite3.connect('db.sqlite',
detect_types=sqlite3.PARSE_DECLTYPES |
sqlite3.PARSE_COLNAMES)
cursor = connection.cursor()
success = 200
unsuccess = 500
default_value = 0
lDefaultEntry = None
for i in range(no_of_gate):
gate_id = i+1
for videofilename in lVideoList:
cursor.execute("SELECT * FROM dailyfootfall WHERE csv_name=? AND gate_id=?", [videofilename, gate_id])
lDefaultEntry = cursor.fetchone()
try:
if lDefaultEntry is not None:
print ('Entry found...!!!')
cursor.execute("UPDATE dailyfootfall SET video_download=?, processed=?, send_status=? ,male_footfall=?, send_status_male=?, "
"female_footfall =?,send_status_female=?, outsiders=?, send_status_outsiders=? "
"WHERE csv_name=? AND gate_id=? AND footfall=0", [unsuccess,unsuccess,unsuccess,default_value,unsuccess,
default_value,unsuccess,default_value,unsuccess,videofilename,gate_id])
print("Data_Updated..!!!")
else:
cursor = connection.cursor()
print ('Entry Not found...!!!')
print("videofilename: ", videofilename)
insert_query = ("INSERT or IGNORE INTO dailyfootfall(csv_name, video_download, processed, footfall, send_status, "
"male_footfall, send_status_male, female_footfall, send_status_female, gate_id,outsiders, send_status_outsiders) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)")
cursor.execute(insert_query,[videofilename, unsuccess, unsuccess, default_value, unsuccess, default_value,
unsuccess, default_value, unsuccess, gate_id, default_value, unsuccess])
print("Data_Inserted..!!")
print("="*20)
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print("Entry found: ",exc_type, fname, exc_tb.tb_lineno)
print("Data Inserted Successfully !")
connection.commit()
cursor.close()
connection.close()
if __name__ == "__main__":
lVideoList = ['2022_01_27_10_00_00-2022_01_25_10_30_00', '2022_01_27_10_30_00-2022_01_25_11_00_00',
'2022_01_27_11_00_00-2022_01_25_11_30_00', '2022_01_27_11_30_00-2022_01_25_12_00_00']
no_of_gate = 3
UpdateData(lVideoList, no_of_gate)
print("default_value inserted!!!!")