sqlite3.OperationalError: 1 values for 3 columns - python-3.x

I am trying to insert and extract data using a sqlite database, but I keep running into this error:
Traceback (most recent call last):
File "Database_Section\Dsite.py", line 14, in <module>
insert("Cup", 4, 5)
File "Database_Section\Dsite.py", line 10, in insert
cur.execute(cur.execute("INSERT INTO store(item, quantity, price) VALUES ('?,?,?')", ('item','quantity','price')))
sqlite3.OperationalError: 1 values for 3 columns`enter code here
And this is my code:
import sqlite3
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS store(item TEXT, quantity INTEGER, price REAL)')
conn.commit()
def insert(item,quantity,price):
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute(cur.execute("INSERT INTO store(item, quantity, price) VALUES ('?,?,?')", ('item','quantity','price')))
conn.commit()
conn.close()
impo
insert("Cup", 4, 5)
def view():
conn = sqlite3.connect('lite.db')
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
conn.close()
return rows
print(view())

"INSERT INTO store(item, quantity, price) VALUES ('?,?,?')"
This tries to insert the literal string '?,?,?' to the table, and fails because it's a single value and there are 3 columns (as the errors says).
You should remove the quotes surrounding the placeholders:
"INSERT INTO store(item, quantity, price) VALUES (?,?,?)"

Related

When create table - Psycopg2.errors.SyntaxError: syntax error at end of input

I have that error
File "/home/darek/PycharmProjects/Small_programs/Analiza_danych_nauka/db_manager.py", line 52, in _execute
self._cur.execute(query)
psycopg2.errors.SyntaxError: syntax error at end of input
LINE 1: ... EXISTS "companys" ("id SERIAL PRIMARY KEY", "name VARCHAR")
I start this code like
db.create_table('companys', ['id SERIAL PRIMARY KEY', 'name VARCHAR'])
next
def create_table(self, table, columns):
create_query = sql.SQL("CREATE TABLE IF NOT EXISTS {} ({})").format(
sql.Identifier(table),
sql.SQL(', ').join(map(sql.Identifier, columns))
)
self._execute(create_query)
and line from error msg
def connect(self):
try:
conn = psycopg2.connect(
user=self.user,
password=self.password,
host=self.host,
port=self.port,
dbname=self.dbname)
# cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur = conn.cursor()
pp(
'------------------------------------------------------------'
'\n-# PostgreSQL connection & transaction is ACTIVE\n'
)
except (Exception, psycopg2.Error) as error:
print(error, sep='\n')
sys.exit()
else:
self._conn = conn
self._cur = cur
self._counter = 0
def _check_connection(self):
try:
self._conn
except AttributeError:
print('ERROR: NOT Connected to Database')
sys.exit()
def _execute(self, query, Placeholder_value=None):
self._check_connection()
if Placeholder_value == None or None in Placeholder_value:
self._cur.execute(query) # 52 line from error msg
print('-# ' + query.as_string(self._conn) + ';\n')
else:
self._cur.execute(query, Placeholder_value)
print('-# ' + query.as_string(self._conn) % Placeholder_value + ';\n')
A suggestion. NOTE: This uses sql.SQL() which does not escape strings and therefore is a SQL injection risk. Make sure you validate the input. It also involves a change in the column listing:
col_list = [
{"col_name": "id", "col_type": "serial", "col_constraint": "primary key"},
{"col_name": "name", "col_type": "varchar", "col_constraint": None}
]
composed_list = []
for col in col_list:
col_cmp = []
col_cmp.append(sql.Identifier(col["col_name"]))
col_cmp.append(sql.SQL(" "))
col_cmp.append(sql.SQL(col["col_type"]))
if col.get("col_constraint"):
col_cmp.append(sql.SQL(" "))
col_cmp.append(sql.SQL(col["col_constraint"]))
composed_list.append(sql.Composed(col_cmp))
base_sql = sql.SQL(
"CREATE TABLE IF NOT EXISTS {table} ({fields})").\
format(table=sql.Identifier("companys"),
fields=sql.SQL(",").join(composed_list)
)
print(base_sql.as_string(con))
CREATE TABLE IF NOT EXISTS "companys" ("id" serial primary key,"name" varchar)
cur.execute(base_sql)
con.commit()
--psql
\d companys
Table "public.companys"
Column | Type | Collation | Nullable | Default
--------+-------------------+-----------+----------+--------------------------------------
id | integer | | not null | nextval('companys_id_seq'::regclass)
name | character varying | | |
Indexes:
"companys_pkey" PRIMARY KEY, btree (id)
After checking SQL class of psycopg2 module as Adrian stated you can provide column names. Because of compasable subclass it parses columns names between doubles quotes(single quote if you use "Literal"). By the way, in order to print the query we should have used as_string method :). Here:
import psycopg2
from psycopg2 import sql
conn_string = "host='localhost' dbname='postgres' user='postgres' password='123123'"
cursor = conn.cursor()
query = sql.SQL("CREATE TABLE IF NOT EXISTS {} ({})").format(sql.Identifier('companys'), sql.SQL(', ').join(map(sql.Identifier, ['id SERIAL PRIMARY KEY', 'name VARCHAR'])))
print(query.as_string(conn))
CREATE TABLE IF NOT EXISTS "companys" ("id SERIAL PRIMARY KEY", "name VARCHAR")
cursor.execute(query)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
psycopg2.ProgrammingError: syntax error at end of input
LINE 1: ... EXISTS "companys" ("id SERIAL PRIMARY KEY", "name VARCHAR")
^
s1 = sql.Literal('id SERIAL PRIMARY KEY')
s2 = sql.Literal('name VARCHAR')
query = sql.SQL("CREATE TABLE IF NOT EXISTS {} ({})").format(sql.Identifier('companys'), sql.SQL(', ').join([s1, s2]))
print(query.as_string(conn))
CREATE TABLE IF NOT EXISTS "companys" ('id SERIAL PRIMARY KEY', 'name VARCHAR')
cursor.execute(query)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
psycopg2.ProgrammingError: syntax error at or near "'id SERIAL PRIMARY KEY'"
LINE 1: CREATE TABLE IF NOT EXISTS "companys" ('id SERIAL PRIMARY KE...
I think, "psycopg2.sql – SQL string" generally are being used to prevent SQL injection in any case of data retrieve operation. You can try to convert you own environment to fit this solution but it is a tailored solution. Because this is a DDL operation you can safely use:
cursor.execute(query)

counting strings through columns

I'm pretty new to python or programming at all so I'd like to get help on the following problem
My table is set up like this:
https://i.imgur.com/KFPq2DI.png
Now I try to count all '✓' and set the number to column Teilnahme.
teilnahmencounter(ctx):
i=0
# Connect
connection = sqlite3.connect("kekse.db")
# cursor
cursor = connection.cursor()
# Abfrage
sql = "SELECT * FROM kekse ORDER BY ID"
cursor.execute(sql)
connection.commit()
for dsatz in cursor:
i = 0
for x in range(2 , 19):
if str(dsatz[x]) == '✓':
i += 1
cursor.execute('UPDATE kekse SET Teilnahme='+str(i)+' WHERE ID=?', dsatz[0]
)
connection.commit()
#print(dsatz[1], i, "Teilnahmen")
connection.close()
Try and use cast in your update where its getting updated -
import sqlite3
# Connect
con = sqlite3.connect("dbname.db")
# cursor
cur = con.cursor()
for row in cur.execute("select * from testtab"):
print(row)
cur.execute("update testtab set id=21 where id = cast("+str(2)+" as int)")
con.commit()
con.close()

SQL UPDATE statement error in python code

I am trying to write a python function that updates a postgres database. The table to be updated is given (department)
Below is the function I wrote:
def modify_dept_budget(deptName, newBudget):
connection = None
try:
connection = connector() # This is a function I wrote to connect so I can hide my credentials.
cursor1 = connection.cursor()
query1 = f"select dept_name from department"
cursor1.execute(query1)
results1 = cursor1.fetchall()
results1 = [result[0] for result in results1]
if deptName in results1:
idx = results1.index(deptName)
print(results1[idx])
cursor2 = connection.cursor()
query = f"UPDATE department SET budget = %s WHERE dept_name == {deptName}"
cursor2.execute(query, [newBudget])
cursor3 = connection.cursor()
cursor3.execute(f'SELECT * FROM department')
results2 = cursor3.fetchall()
headers = [item[0] for item in cursor3.description]
df = pd.DataFrame(data = results2, columns = headers)
print(df)
except(Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if connection:
cursor1.close()
cursor2.close()
cursor3.close()
connection.close()
When I run modify_dept_budget('Music', 85000), I get the following error:
Music
column "music" does not exist
LINE 1: ...PDATE department SET budget = 85000 WHERE dept_name == Music
^
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-77-16e7278e3358> in <module>
----> 1 modify_dept_budget('Music', 85000)
<ipython-input-76-80361b6ddf35> in modify_dept_budget(deptName, newBudget)
26 cursor1.close()
27 cursor2.close()
---> 28 cursor3.close()
29 connection.close()
UnboundLocalError: local variable 'cursor3' referenced before assignment
Can anyone help me figure out what is going on?
You have two problems. First, SQL does not use the double == for the equality test. Just plain =. Second, that string literal needs to be quoted. Unless you need a table name or a field name, you won't be using f-strings with SQL. So, do:
query = "UPDATE department SET budget = %s WHERE dept_name = %s"
cursor2.execute(query, [newBudget, deptName])

table as var in cur.execute

I'm noob at python, and I'm trying to do some operations in some tables.
At the moment I'm doing this with hard coding the tables:
cur.execute("select id,email from table1;")
but I'm want to change the tables to and variable to construct a function, like:
cur.execute("select id,email from table;")
How I can do this?
Many thanks
I'm using python3 with psycopg2
#open connection with db
conn = psycopg2.connect(host="localhost",database="test", user="test", password="test")
cur = conn.cursor()
#Select id
cur.execute("select id,email from customers;")
#put ids on list
row = cur.fetchone()
Also I tried this:
sql = "select id,email from %s"
val = customers
cur.execute(sql, val)
And I have this error:
File "updateemails.py", line 14, in <module>
val = (customers)
NameError: name 'customers' is not defined```

Insert 2 date values into columns in sqlite db using python

New to using sqlite with python. I am trying to insert two date values into two date columns in sqlite db via Python.
import sqlite3
def create_connection(db_file):
# Create a database connection to a SQLite database
# Param: db_file as str. Return: connection objects or None
try:
conn = sqlite3.connect(db_file)
cur = conn.cursor()
return conn, cur
except Error as e:
print (e)
return None
my_conn, my_cur = create_connection(dpd_sqlite_db_dir)
def create_sqlite_table_if_nonexist(conn, table_name):
sql = 'create table if not exists '+table_name+' (data_download_date datetime, script_executed_date datetime)'
conn.execute(sql)
create_sqlite_table_if_nonexist(my_conn, 'df_timestamp_en')
def insert_timestamp(conn, timestamp):
# execute insert into db
sql = ''' INSERT INTO df_timestamp_en (data_download_date, script_executed_date) VALUES(?,?) '''
cur = conn.cursor()
cur.execute(sql, timestamp)
return cur
timestamp_info = ('2018-10-30', '2018-11-30')
insert_timestamp(my_conn, timestamp_info)
It runs and created the table with two date columns, but it doesn't insert the timestamp_info's values.

Resources