sqlite3.OperationalError: no such column: - Python - python

I am trying to Inserat something from Input into my Database. But getting the Error:
sqlite3.OperationalError: no such column: kundename
import sqlite3
conn = sqlite3.connect('datenbank.db')
print ("Opened database successfully")
kundenname= input("Kundename: ")
auftragstyp= input("Auftragstyp: ")
auftragsurl= input("Auftragsurl: ")
anzahl= input("Anzahl der Bewertungen: ")
conn.execute("INSERT INTO kundenname VALUES (kundename,auftragstyp,auftragsurl,anzahl)", (kundenname, auftragstyp, auftragsurl, anzahl))
conn.commit()
print ("Records created successfully")
conn.close()
But if I make like:
import sqlite3
conn = sqlite3.connect('datenbank.db')
print ("Opened database successfully")
conn = conn.execute("SELECT ID, kundename from kundenname")
for row in conn:
print ("ID = ", row[0])
print ("kundename = ", row[1])
print ("Operation done successfully")
conn.close()
then it works and Shows me the Datas in the Base. But why insert saying the colum dosent excist?
Thank you very much!

I think you have a problem with this line:
conn.execute("INSERT INTO kundenname VALUES
(kundename,auftragstyp,auftragsurl,anzahl)", (kundenname, auftragstyp,
auftragsurl, anzahl))
This is not the way to insert, try this:
conn.execute("INSERT INTO kundenname
('kundename','auftragstyp','auftragsurl','anzahl') VALUES (" +
str(kundename) +"," + str(auftragstyp) + "," + str(auftragsurl) + ","
+ str(anzahl)+")"

The interpreter is complaining about your using unquoted strings. It's interpreting them as variable names in your insert statement. Try this:
conn.execute("INSERT INTO kundenname ('kundename','auftragstyp','auftragsurl','anzahl') VALUES (kundenname, auftragstyp, auftragsurl, anzahl)")

Related

SQLite + Python Data not saved in DB file

This is my first project with SQLite.
The code runs perfect I checked and the lines look perfect.
I supposed that due to lack of knowledge of SQLite I'm making a mistake.
Problem: The code runs perfect no problem. But when I finish it doesn't print the values or even save the values in the .db file.
Full Code:
import sqlite3
import datetime
import time
conn = sqlite3.connect('covid.db')
c = conn.cursor()
def create_table():
c.execute('''CREATE TABLE IF NOT EXISTS
covidTrack(
name TEXT,
email TEXT,
ph_number INTEGER,
datestamp TEXT,
keyword TEXT)''')
i_name = input('Please insert FULL NAME : \n ...')
i_email = input('Please insert EMAIL : \n ...')
i_number = input('Please insert PHONE NUMBER : \n ...')
print('Your data has been saved for acelerated contact, thank you.')
time.sleep(3)
def data_entry():
c.execute('INSERT INTO covidTrack VALUES(?,?,?)',
(i_name, i_email, i_number))
conn.commit()
def dynamic_data_entry():
keyword = nameofvenue
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%M-%D %h:%m:%s'))
c.execute('INSERT INTO covidTrack VALUES(date, keyword)')
conn.commit()
def read_from_db():
c.execute('''SELECT * FROM covidTrack
WHERE datestamp
BETWEEN "2021-02-06 14:50:00" AND "2021-02-06 15:00:00"''')
conn.commit()
for row in c.fetchall():
print(row)
create_table()
data_entry()
dynamic_data_entry()
read_from_db()
c.close()
conn.close()
I suppose if something wrong with the way I use conn.commit().
import sqlite3
import datetime
import time
conn = sqlite3.connect('covid.db')
c = conn.cursor()
def create_table():
c.execute('''CREATE TABLE IF NOT EXISTS
covidTrack(
name TEXT,
email TEXT,
ph_number INTEGER,
datestamp TEXT,
keyword TEXT)''')
i_name = input('Please insert FULL NAME : \n ...')
i_email = input('Please insert EMAIL : \n ...')
i_number = input('Please insert PHONE NUMBER : \n ...')
print('Your data has been saved for acelerated contact, thank you.')
time.sleep(3)
def data_entry():
date, keyword = dynamic_data_entry()
c.execute('INSERT INTO covidTrack VALUES(?, ?, ?, ?, ?)', (i_name, i_email, i_number, date, keyword))
conn.commit()
def dynamic_data_entry():
keyword = 'nameofvenue'
date = str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%M-%D %h:%m:%s'))
return date, keyword
def read_from_db():
c.execute('''SELECT * FROM covidTrack''')
conn.commit()
create_table()
data_entry()
read_from_db()
for row in c.fetchall():
print(row)
c.close()
conn.close()
change the code below (make the commit call part of the function that insert the data). Do it in dynamic_data_entry as well
def dynamic_data_entry():
keyword = nameofvenue
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%M-%D %h:%m:%s'))
c.execute('INSERT INTO covidTrack VALUES(date, keyword)')
conn.commit()
to
def dynamic_data_entry():
keyword = nameofvenue
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%M-%D %h:%m:%s'))
c.execute('INSERT INTO covidTrack VALUES(date, keyword)')
conn.commit()
You do not actually commiting your executes. Move conn.commit after actual executes.

Unknown column error when trying to add data to table in mysql database in Python

I get this error when adding data to the database.
How do I solve this?
Error:
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'hn' in 'field list'
I know this column does not exist but I am not sending data to such a column anyway.
My Python code:
def addToTable(table_name,connection,column_name_list,*data_list):
if(len(column_name_list) != len(data_list)):
raise ValueError("'column_name_list' length has to be equal to 'data_list' length. Please check the parameters")
cursor = connection.cursor() # initializing a cursor
for column_data in range(len(data_list[0])):
addList = list()
for data in range(len(data_list)):
added = str(data_list[data][column_data])
addList.append(added)
cursor.execute("INSERT INTO " + table_name + " VALUES (" + ", ".join(str(k) for k in addList) + ")")
mydb.commit()
print("Added {} in {} ...".format(added, table_name))
Sample query sent from python code:
INSERT INTO deneme VALUES (hn, 1212, asdmailcom)
calling the function:
names = ["hn","ben","alex",]
numbers = [1212,1245,54541]
mails = ["asdmailcom","fghmailcom","xyzmailcom"]
columns = ["de","ne","me"]
mydb = mysql.connector.connect(host="127.0.0.1",
user="root",
passwd="1234",
database="deneme",
auth_plugin='mysql_native_password')
addToTable("deneme",mydb,columns,names,numbers,mails)
My table name is 'deneme', database name is 'deneme'. Columns : 'de' varchar(45), 'ne' varchar(45), 'me' varchar(45)
I solved the problem. I explained in the comment lines.
def addToTable(table_name,connection,column_name_list,*data_list):
if(len(column_name_list) != len(data_list)):
raise ValueError("'column_name_list' length has to be equal to 'data_list' length. Please check the parameters")
cursor = connection.cursor() # initializing a cursor
for column_data in range(len(data_list[0])):
addList = list()
for data in range(len(data_list)):
added = str(data_list[data][column_data])
added = "'"+added+"'" # the purpose of this line is to convert the data to string
# example: without this line
# query ---> INSERT INTO table_name (column1, column2, ...) VALUES (lorem,ipsum,sit)
# example: with this line
# query ---> INSERT INTO table_name (column1, column2, ...) VALUES ('lorem','ipsum','sit')
addList.append(added)
cursor.execute("INSERT INTO " + table_name + " VALUES (" + ", ".join(str(k) for k in addList) + ")")
mydb.commit()
print("Added {} in {} ...".format(added, table_name))

MySQL db call: not all arguments converted during string formatting

I get the error not all arguments converted during string formatting, when I execute the below-given code:
pro_title = "FSBT"
print "pro_title: " + pro_title
pro_id_query = "SELECT ID FROM projs WHERE pro_title=%s"
cursor.execute(pro_id_query, pro_title)
db.commit()
row = cursor.fetchone()
pro_id = None
if row is not None:
pro_id = str(row[0])
print "pro_id: " + pro_id
I also tried format:
pro_id_query = "SELECT ID FROM projs WHERE title={}"
cursor.execute(pro_id_query.format(pro_title))
It only works when I use ' around {}:
pro_id_query = "SELECT ID FROM projs WHERE title='{}'"
cursor.execute(pro_id_query.format(pro_title))
I do not understand why INSERT queries work well with %s, while SELECT queries do not:
insert_query = "INSERT INTO projs (title, description) VALUES (%s, %s) ON DUPLICATE KEY UPDATE `title`=%s"
cursor.execute(insert_query, (pro_title, pro_description, pro_title))
pro_title = "FSBI"
pro_id_query = "SELECT * FROM %s"%(pro_title)
cursor = con.cursor()
cursor.execute(q)
result_list = result.fetchall()
result_list[0][0]
con.commit()
con.close()
pro_id_query = cursor.fetchone() while row != False:
print ("The ID is : ", row[0])
*edit
id = input("Id : ")
name = input("Name : ")
cursor = con.cursor()
cursor.execute(""" INSERT INTO names (id, name) VALUES("%s", "%s")"""
%(id, name))

Python/postgres/psycopg2: getting ID of row just inserted

I'm using Python and psycopg2 to interface to postgres.
When I insert a row...
sql_string = "INSERT INTO hundred (name,name_slug,status) VALUES ("
sql_string += hundred_name + ", '" + hundred_slug + "', " + status + ");"
cursor.execute(sql_string)
... how do I get the ID of the row I've just inserted? Trying:
hundred = cursor.fetchall()
returns an error, while using RETURNING id:
sql_string = "INSERT INTO domes_hundred (name,name_slug,status) VALUES ("
sql_string += hundred_name + ", '" + hundred_slug + "', " + status + ") RETURNING id;"
hundred = cursor.execute(sql_string)
simply returns None.
UPDATE: So does currval (even though using this command directly into postgres works):
sql_string = "SELECT currval(pg_get_serial_sequence('hundred', 'id'));"
hundred_id = cursor.execute(sql_string)
Can anyone advise?
thanks!
cursor.execute("INSERT INTO .... RETURNING id")
id_of_new_row = cursor.fetchone()[0]
And please do not build SQL strings containing values manually. You can (and should!) pass values separately, making it unnecessary to escape and SQL injection impossible:
sql_string = "INSERT INTO domes_hundred (name,name_slug,status) VALUES (%s,%s,%s) RETURNING id;"
cursor.execute(sql_string, (hundred_name, hundred_slug, status))
hundred = cursor.fetchone()[0]
See the psycopg docs for more details: http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries
I ended up here because I had a similar problem, but we're using Postgres-XC, which doesn't yet support the RETURNING ID clause. In that case you can use:
cursor.execute('INSERT INTO ........')
cursor.execute('SELECT LASTVAL()')
lastid = cursor.fetchone()['lastval']
Just in case it was useful for anyone!
Consider a RETURNING clause http://www.postgresql.org/docs/8.3/static/sql-insert.html
For me, neither ThiefMaster's answer worked nor Jamie Brown's. What worked for me was a mix of both, and I'd like to answer here so it can help someone else.
What I needed to do was:
cursor.execute('SELECT LASTVAL()')
id_of_new_row = cursor.fetchone()[0]
The statement lastid = cursor.fetchone()['lastval'] didn't work for me, even after cursor.execute('SELECT LASTVAL()'). The statement id_of_new_row = cursor.fetchone()[0] alone didn't work either.
Maybe I'm missing something.
ThiefMaster's approach worked for me, for both INSERT and UPDATE commands.
If cursor.fetchone() is called on a cursor after having executed an INSERT/UPDATE command but lacked a return value (RETURNING clause) an exception will be raised: ProgrammingError('no results to fetch'))
insert_query = """
INSERT INTO hundred (id, name, name_slug, status)
VALUES (DEFAULT, %(name)s, %(name_slug)s, %(status)s)
RETURNING id;
"""
insert_query_values = {
"name": "",
"name_slug": "",
"status": ""
}
connection = psycopg2.connect(host="", port="", dbname="", user="", password="")
try:
with connection:
with connection.cursor() as cursor:
cursor.execute(insert_query, insert_query_values)
num_of_rows_affected = cursor.rowcount
new_row_id = cursor.fetchone()
except psycopg2.ProgrammingError as ex:
print("...", ex)
raise ex
finally:
connection.commit()
connection.close()

Python and sqlite trouble

I can't show the data from database sqlite in python.
connection = sqlite3.connect('db')
connection.cursor().execute('CREATE TABLE IF NOT EXISTS users ( \
id TEXT, \
name TEXT, \
avatar TEXT \
)')
# In cycle:
query = 'INSERT INTO users VALUES ("' + str(friend.id) + '", "' + friend.name + '", "' + friend.avatar +'" )'
print query
connection.cursor().execute(query)
connection.commit()
# After cycle
print connection.cursor().fetchall()
Sample output of query variable:
INSERT INTO users VALUES ("111", "Some Name", "http://avatar/path" )
In result, fetchall returns empty tuple. Why?
UPD
Forgotten code:
connection.cursor().execute('SELECT * FROM users')
connection.cursor().fetchall()
→
[]
INSERT does not return data. To get the data back out, you'll have to issue a SELECT statement.
import sqlite3
con = sqlite3.connect("db")
con.execute("create table users(id, name, avatar)")
con.execute("insert into users(id, name, avatar) values (?, ?, ?)", (friend.id, friend.name, friend.avatar))
con.commit()
for row in con.execute("select * from users")
print row
con.close()
Because the create table string as displayed is syntactically invalid Python, as is the insert into string.
Actually, the answer to your first question is: because you use different cursors.
connection.cursor() creates a new cursor in the connection you created before. fetchall() gives you the results of the query you executed before in that same cursor. I.e. what you did was this:
# After cycle
cursor1 = connection.cursor()
cursor1.execute('SELECT * FROM users')
cursor2 = connection.cursor()
cursor2.execute("")
cursor2.fetchall()
What you should have done was this:
# After cycle
cursor = connection.cursor()
cursor.execute('SELECT * FROM users')
print cursor.fetchall()

Categories

Resources