I have a problem with deleting a record from my SQLite3 database:
conn = sqlite3.connect('databaza.db')
c = conn.cursor()
data3 = str(input('Please enter name: '))
mydata = c.execute('DELETE FROM Zoznam WHERE Name=?', (data3,))
conn.commit()
c.close
Everything is OK, no errors, but the delete function doesn't work!
Does anyone have an idea?
The correct syntax for a parameterized query is:
mydata = c.execute("DELETE FROM Zoznam WHERE Name=?", (data3,))
Make sure the parameter uses the comma, to make it a python tuple.
This will help prevent SQL Injection which is possible when passing in a formatted string. More on SQL Injection here
Related post here.
I'm a little late to the party but if you Google search "python sqlite delete row" This is the first thing that comes up and I was having the same issue where things were not getting DELETE'd from my sqlite DB.
I'm using Python 2.7 on Debian Jessie.
Previously, when I wrote Python code for adding and retrieving information in the sqlite database, I had written the commands with correct capitalization where needed and it worked.
curs.execute("SELECT example_column1 FROM example_table WHERE example_column2=(?)", (Variable,))
However...
curs.execute("DELETE FROM example_table WHERE example_column1=(?)", (Variable,)):
This for some reason does not work with the DELETE command. I had to send that command in all lower-case before sqlite would respect the command being sent.
conn=sqlite3.connect('example.db')
curs=conn.cursor()
curs.execute("delete from example_table where example_column=(?)", (Variable,))
conn.commit()
conn.close()
I have no idea why.
I tried all the previously mentioned methods but having the command sent in lowercase was the only way I could get it to work.
Hope this helps any struggling neophytes in their journey into Python and sqlite.
Try with:
mydata = c.execute('DELETE FROM Zoznam WHERE Name = (?)', (data3))
Without the ',' and the '?' between '()'
I'm using Python 3.9 on windows.
c.execute("DELETE FROM Zoznam WHERE Name={0}".format(data3))
conn.commit()
I advise you to first make a string for the query , and then execute it. ex:
query = "delete from zoznam where name = '%s' " % data3
c.execute(query)
conn.commit()
Check the file permissions.
An aside, I prefer the tokenized method:
mydata = c.execute("DELETE FROM Zoznam WHERE Name='%s'" % data3)
Thank you to everybody who tried to help. The right code is:
conn = sqlite3.connect('databaza.db')
c = conn.cursor()
conn.text_factory = str
data3 = str(input('Please enter name: '))
query = "DELETE FROM Zoznam WHERE Name = '%s';" % data3.strip()
print(query)
mydata = c.execute(query)
Related
I am trying to get Information from my database, and print it, but unfortunately, Instead of Printing the Information from the Table, it just Prints 0 or 1.
Why does it do this?
Can someone please help me?
sql = ("SELECT code FROM testing WHERE email = ((%s))")
sql2 = a.execute(sql, (fullemail))
sqlusername = ("SELECT username FROM testing123 WHERE code = ((%s))")
username = a.execute(sqlusername, (sql2))
print("Test3")
print(username)
Thank you.
The execute() method just returns the number of impacted rows.
You must use .fetchall() or equivalent (e.g. .fetchone()...) DBAPI methods to get a resultset.
Also, using parentheses alone around a single value: (fullemail) will not be recognized as a tuple, you need to explicitly add a comma so Python will recognize this as a tuple: (fullemail, )
sql = ("SELECT code FROM testing WHERE email = %s")
a.execute(sql, (fullemail, ))
sql2 = a.fetchall()
print(sql2)
sqlusername = ("SELECT username FROM testing123 WHERE code = %s")
a.execute(sqlusername, (sql2[0][0], ))
username = a.fetchall()
print("Test3")
print(username)
Depending on which library you are using:
MySQLdb (python 2.7)
mysqlclient (MySQLdb for python3)
PyMySQL (pure Python)
You can also use a DictCursor to get your result set rows as dict instead of list. Usage is like:
from pymysql.cursors import DictCursor
import pymysql
db = pymysql.connect(host="", user="", passwd="", cursorclass=DictCursor)
with db.cursor() as cur:
cur.execute("SELECT ...")
results = cur.fetchall()
This will give you a list of dictionaries instead of a list of lists.
I am trying to use cx_Oracle to execute an sql statement from Python. The SQL I have written seems to work in my Oracle database client (SQL Developer) but seems to pull back every record when executed from the Python script
#setup db connection here...
curs = db.cursor()
sql=("\
SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,\
FIRST_DB.second_table b,\
OTHER_DB.third_table c\
\
WHERE\
a.identifier='XXXX' and\
a.this_row = b.that_row and\
b.this_row = c.that_row;\
")
curs.execute(sql)
print curs.description
result=curs.fetchmany()
while result:
for i,j,k,l in result:
print i,j,k,l
result=curs.fetchmany()
db.close()
This returns every record in the view and not just the one containing 'XXXX' as it does in the SQL developer...
Can anyone see either a problem in the SQL or in the way I am doing this?
Cheers in advance
Try to use triple-quoted strings. It is a good way to have readable multi-line strings. I don't have an Oracle DB to test here, but I am guessing the lack of white space is causing you problems.
Print your SQL statement and you will see how it actually looks with the backslashes removed:
sql=("\
SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,\
FIRST_DB.second_table b,\
OTHER_DB.third_table c\
\
WHERE\
a.identifier='XXXX' and\
a.this_row = b.that_row and\
b.this_row = c.that_row;\
")
>>> print sql
SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,FIRST_DB
.second_table b,OTHER_DB.third_table cWHEREa.identifier='XXXX' anda.this_row = b
.that_row andb.this_row = c.that_row;
As far as I know, some tools like SQL*Plus have problems with blank lines inside a sql statement. Not sure how Python passes your statement to the DB, but maybe taking out that blank line before your where-clause will help:
#setup db connection here...
curs = db.cursor()
sql=("\
SELECT a.first, c.second, c.third, c.fourth FROM FIRST_DB.first_table a,\
FIRST_DB.second_table b,\
OTHER_DB.third_table c\
WHERE\
a.identifier='XXXX' and\
a.this_row = b.that_row and\
b.this_row = c.that_row;\
")
curs.execute(sql)
print curs.description
result=curs.fetchmany()
while result:
for i,j,k,l in result:
print i,j,k,l
result=curs.fetchmany()
db.close()
I have this code in Python:
conn = sqlite3.connect("people.db")
cursor = conn.cursor()
sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)
conn.commit()
sql = 'insert into people VALUES (3, "test")'
cursor.execute(sql)
conn.commit()
sql = 'insert into people VALUES (5, "test")'
cursor.execute(sql)
conn.commit()
print 'Printing all inserted'
cursor.execute("select * from people")
for row in cursor.fetchall():
print row
cursor.close()
conn.close()
But seems is never saving to the database, there is always the same elements on the db as if it was not saving anything.
On the other side If I try to access the db file via sqlite it I got this error:
Unable to open database "people.db": file is encrypted or is not a database
I found on some other answers to use conn.commit instead of conn.commit() but is not changing the results.
Any idea?
BINGO ! people! I Had the same problem. One of thr reasons where very simple. I`am using debian linux, error was
Unable to open database "people.db": file is encrypted or is not a database
database file was in the same dir than my python script
connect line was
conn = sqlite3.connect('./testcases.db')
I changed this
conn = sqlite3.connect('testcases.db')
! No dot and slash.
Error Fixed. All works
If someone think it is usefull, you`re welcome
This seems to work alright for me ("In database" increases on each run):
import random, sqlite3
conn = sqlite3.connect("people.db")
cursor = conn.cursor()
sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)
for x in xrange(5):
cursor.execute('insert into people VALUES (?, "test")', (random.randint(1, 10000),))
conn.commit()
cursor.execute("select count(*) from people")
print "In database:", cursor.fetchone()[0]
You should commit after making changes i.e:
myDatabase.commit()
can you open the db with a tool like sqlite administrator ? this would proove thedb-format is ok.
if i search for that error the solutions point to version issues between sqlite and the db-driver used. maybe you can chrck your versions or AKX could post the working combination.
regards,khz
Hi im having issues with a sql query it works perfect in console, but when i implement into python it seems to work perfect no errors but when i check the database it hasnt worked, yet with the console it does work the same no errors yet when i check db the data is there... exact same query i use.
Any ideas?
UPDATE ex SET fbsiteurl = stringvarible, fbsitesource = '' WHERE id = 23123;
in python:
cur = con.cursor()
sqlquery = "UPDATE ex SET fbsiteurl = '"+somevarible+"', fbsitesource = '"+somevarible+"' WHERE id = %d;" % recordid
print sqlquery
cur.execute(sqlquery)
query shows up fine in print no issues, if i copy the print out and paste it into a mysql console it works perfect everytime, just come python it acts like it works but dosnt really 0_o
connection.autocommit(), or you need to do connection.commit()
Been there :) you need to close the cursor
This little gotcha continues to this day. Just to clarify, I had to use both of the above answers, as in:
cur = self.db.cursor()
try:
cur.execute(sqlcommand)
self.db.commit()
res = cur.fetchall()
except res is not None:
print(res)
finally:
cur.close()
I have created a database with MySQLdb.
In database I have a table with name student with columns:
id(is int),
id_user(is int),
f_name(is str),
l_name(is str)
I want to update a row.
My code is below:
db=mdb.connect(host="localhost", use_unicode="True", charset="utf8",
user="", passwd="", db="test")
# prepare a cursor object using cursor() method
cursor = db.cursor()
sql="""SELECT id_user FROM student"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
rows = cursor.fetchall()
the=int(7)
se=str('ok')
for row in rows:
r=int(row[0])
if r==the:
sql2 = """UPDATE student
SET f_name=%s
WHERE id_user = %s"""% (se,the)
# Execute the SQL command
cursor.execute(sql2)
# Commit your changes in the database
db.commit()
db.rollback()
# disconnect from server
db.close()
When I run it I take the error there is column with name ok why?
Can anyone help me find what I am doing wrong please?
str doesn't wrap its argument in quotation marks, so your statement is this:
UPDATE student SET f_name=ok WHERE id_user = 7
when it needs to be this:
UPDATE student SET f_name='ok' WHERE id_user = 7
So, either change this line:
SET f_name=%s
to this:
SET f_name='%s'
or else change this line:
se=str('ok')
to this:
se="'" + str('ok') + "'"
Though I recommend reading about SQL injection, which will become a concern as soon as you start using user-supplied data instead of hard-coded values.
You should run the query like this:
sql2 = """UPDATE student
SET f_name = %s
WHERE id_user = %s"""
cursor.execute(sql2, (se, the))
Don't use string interpolation, let the database driver handle passing the parameters for you. Otherwise you have to deal with syntax errors like this, or worse, SQL injection.
More details here.
You should always enclose your data with quotes.
Instead of %s solely use '%s' the only types you dont need it are numeric ones, but even there i would enclose %d with '%d' cos it is more save.
And you should use at least db.escape_string(your_data) before inserting or updating same values into your database.
Or have a look at the pdo-using style of mysqldb:
http://mysql-python.sourceforge.net/MySQLdb.html#some-examples
c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
WHERE price < %s""", (max_price,))