MySQLdb - Check if row exists Python - python

I am trying to check if a row exist with the same Name my database with python and can't quite get it here is what I am trying: (I know the connection is wokring)
try:
cursor.execute("SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name"), (item_name)
catch:
print "it does not exist"
Can someone help me out here
Thanks

First of all you have a wrong syntax in your code. Python doesn't have a try...catch block. It has try...except block which is used like this:
try:
# something here
except:
# something here
MySQL does not return an error when you use SELECT command. However there are two different ways you can find out if it returned something or not.
PYTHON 2.7
cursor.execute(
"SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
(item_name,)
)
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print "number of affected rows: {}".format(row_count)
if row_count == 0:
print "It Does Not Exist"
PYTHON 3+
cursor.execute(
"SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
(item_name,)
)
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print ("number of affected rows: {}".format(row_count))
if row_count == 0:
print ("It Does Not Exist")
Another way to do this would be to fetch the statement and check if it is empty:
# execute statement same as above
msg = cursor.fetchone()
# check if it is empty and print error
if not msg:
print 'It does not exist'
This is my first answer, so I don't know how to style the code in the answer properly, it also seems messy because of that. Sorry for that.
Also i use Python 3 and pymysql, so there may be some syntax error but I have tried to write the code according to python 2.7 from what I could remember about it.
EDIT (5/1/2020)
Thanks to #Arishta for pointing out that the first method will require you to fetch all rows before using row_count. i.e adding cursor.fetchall() before the row_count = cursor.rowcount
cursor.execute(
"SELECT Name, COUNT(*) FROM Item_Info WHERE Name = %s GROUP BY Name",
(item_name,)
)
# Add THIS LINE
results = cursor.fetchall()
# gets the number of rows affected by the command executed
row_count = cursor.rowcount
print("number of affected rows: {}".format(row_count))
if row_count == 0:
print("It Does Not Exist")
Use the cursor.fetchone() if you only care if the record exists or not.

If you want to check for empty results, try if cur.description is None:
if cursor.description is None:
# No recordset for INSERT, UPDATE, CREATE, etc
pass
else:
# Recordset for SELECT
As well as:
exist = cursor.fetchone()
if exist is None:
... # does not exist
else:
... # exists
If you are running a statement that would never return a result set
(such as INSERT without RETURNING, or SELECT ... INTO), then you
do not need to call .fetchall(); there won't be a result set for
such statements. Calling .execute() is enough to run the statement.

cursor.execute("SELECT * FROM userinfo WHERE User_Name=%s",(userid,))
data="error" #initially just assign the value
for i in cursor:
data=i #if cursor has no data then loop will not run and value of data will be 'error'
if data=="error":
print("User Does not exist")
else:
print("User exist")

Related

how to update data only if the sql query we have entered exists through python?

I want to update one table in mysql which has 3 rows
what i want is to update any row with update command but this has to be happened only when there exists a particular row
i.e.if i update it like updatedata = "update table12 set name='Dhiraj', city='Delhi' where id=25"
then it should give me an error
Here is my code:
import pymysql
db = pymysql.connect('localhost','root','','firstdb')
print("database connected successfully")
cur = db.cursor()
updatedata = "update table12 set name='Dhiraj', city='delhi' where id=25"
if updatedata:
try:
cur.execute(updatedata)
db.commit()
print("Data updated successfully...")
except:
print("Something went wrong!")
else:
print("There is no any data you entered!")
cur.execute() returns the number of affected rows:
https://pymysql.readthedocs.io/en/latest/modules/cursors.html#pymysql.cursors.Cursor.execute
So you should be able to do something like:
updated_rows = cur.execute(updatedata)
if updated_rows > 0:
print("success")
else:
print("no matching rows")
This updates all rows based on a condition over the same table
UPDATE tbl
SET field_to_update = CASE
WHEN (SELECT COUNT(*) FROM (SELECT * FROM tbl) AS copy WHERE copy.field=<condition> HAVING COUNT(*)>0) THEN "this_value_if_true"
ELSE field_to_update
END

PyMySQL Only returns query correctly first time round

Please consider the following:
I have a Python script that constantly checks a Database for new content by running a query.
def getTasks(database):
print "Checking for new tasks"
query = 'SELECT * FROM fosbot_tasks WHERE asked = %s'
args = (0)
try:
with database.cursor() as cursor:
cursor.execute(query, args)
return cursor.fetchall()
except database.Error as e:
print e
When the script first starts it returns all the correct data, however several seconds later it will re-run this function, I still see the "Checking for new tasks" in the console, however nothing is returned, no matter what is in the database.
If new content is added to the database where 'asked' is '0' it will not be picked up, nor if I change another already processed row (where asked == 1) back to 0, it just stays at 0 and is never found by the query.
Is there some sort of query response caching I am not aware of?
Any assistance will be appreciated.
Edit
Using the following:
def getTasks(database):
query = 'SELECT * FROM fosbot_tasks WHERE asked = %s'
args = (0,)
try:
with database.cursor() as cursor:
print "Checking for new tasks"
number_of_rows=cursor.execute(query, args)
print number_of_rows
return cursor.fetchall()
except database.Error as e:
print e
Results in:
Checking for new tasks
0
Checking for new tasks
0
Checking for new tasks
0
etc etc

How do you read individual values from the same row in a database with sqlite?

I am attempting to read 2 values from the same row in a database but I am only good enough to read the entire line at once. I have added all the code that I think will be relevant:
def find(search, term):
# Helper function for the find function.
with connect("GTINb.db") as db:
cursor = db.cursor()
sql = "select * from GTINb where {} = ?".format(search)
cursor.execute(sql,(term,))
db.commit()
results = cursor.fetchall()
new = str(term)
if results:
results = str(results)
temp = open('temp.txt', 'a')
temp.write(results)
temp.write('\n')
temp.close()
with connect("GTINb.db") as db:
cursor.execute("UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8=(?)",(new,))
cur = cursor.execute("SELECT stockcur from GTINb by (?)",(new,))
re = cursor.execute("SELECT restock from GTINb by (?)",(new,))
if cur < re:
cursor.execute("UPDATE GTINb SET stockcur=stockcur+10 WHERE GTIN8=(?)",(new,))
return print('More stock has been ordered in as stocks were low')
else:
return
else:
temp = open('temp.txt', 'a')
temp.write('Product not found')
temp.write('\n')
temp.close()
return
I am currently getting the error sqlite3.OperationalError: near "(": syntax error, and have tried replacing the '(?)' with %s, (%s) and ? with no success, coming up with the following error messages:
sqlite3.OperationalError: near "12345670": syntax error // where 12345670 was the input represented by new
sqlite3.OperationalError: near "(": syntax error
sqlite3.OperationalError: near "?": syntax error
Is there another way of doing this or have I made a simple mistake?
None of the SQL statements you've written are valid SQL. Please consult the SQLite documentation for the valid syntax.
Briefly:
UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8=(?)
SELECT stockcur from GTINb by (?)
SELECT restock from GTINb by (?)
should be
UPDATE GTINb SET stockcur=stockcur-1 WHERE GTIN8 = ?
SELECT stockcur FROM GTINb WHERE GTIN8 = ?
SELECT restock FROM GTINb WHERE GTIN8 = ?
although the first one will probably execute with the unneeded parentheses.
Once you have your SQL working you will find that the second two statements can be combined into
SELECT stockcur, restock FROM GTINb WHERE GTIN8 = ?
which I believe is what you were asking about.

How can I check if SQLite cursor result from a SELECT statement is empty?

I've tried using fetchone() and it works, but the problem is that it removes the first entry from the list in the cases where I do have items in the result.
results = cursor.execute('SELECT ID, text FROM mytable')
if results.fetchone() is None:
print "**********"
print "No entries"
print "**********"
else:
for row in results:
print "\t%s: %s" % (row[0], row[1])
Is there a way to find out if "results" is empty without fetching from it?
SQLite is somewhat awkward like that as you have to .fetchone() to see if you get a result. There is a read-ahead work-around though (which can be used on iterables in general).
from itertools import chain
try:
first_row = next(results)
for row in chain((first_row,), results):
pass # do something
except StopIteration as e:
pass # 0 results
No. rowcount exists but is always -1.
res = cursor.execute('SELECT ID, text FROM mytable')
try:
first_row = res.next()
for row in [first_row] + res.fetchall():
print '\t%s: %s' % (row[0], row[1])
except StopIteration as e:
print 'No entries'
Use the cursor to fetching records not a result variable because cursor not return any values, so replace this :
$ results = cursor.execute('SELECT ID, text FROM mytable')
$ if cursor.fetchone() is None:
$ print "**********"
$ print "No entries"
$ print "**********"
$ else:
$ for row in cursor:
print "\t%s: %s" % (row[0], row[1])
Now it will work...
This isn't the most elegant, but it should work right?
results = cursor.execute('SELECT ID, text FROM mytable')
done_stuff = False
for row in results:
done_stuff = True
# do the stuff you want to do
if not done_stuff:
print("didn't do stuff")
It doesn't matter if you do the check at the end as the for-loop is going to end instantly with an empty result set.

Number of rows inserted into SQLite db is negative

I'm trying to insert new records into SQLite database from Python code.
con = sqlite.connect(connectionString)
cur = con.cursor()
countOfNewItems = 0
for ...
try:
con.execute("insert or ignore into items ...")
countOfNewItems += cur.rowcount
except:
cur.close()
con.close()
print "Error when inserting item '%s' to database." % item
exit(1)
cur.close()
con.commit()
con.close()
print "%d new items have been inserted." % countOfNewItems
My code reports negative number of inserted records (-5141).
Because my database was empty, I could find out how many records were inserted via command line
select count(*) from items;
4866
Could you advise me what's wrong. Why the two values don't match and why it's negative?
http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.rowcount
Although the Cursor class of the sqlite3 module implements this attribute, the database engine’s own support for the determination of “rows affected”/”rows selected” is quirky.
and
As required by the Python DB API Spec, the rowcount attribute “is -1 in case no executeXX() has been performed on the cursor or the rowcount of the last operation is not determinable by the interface”.
Try cur.execute instead of con.execute. cur.rowcount then returns 1 for me for a simple insert.

Categories