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...catch
block. It has try...except block which is used like this:try:
# something here
except:
# something here
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.
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")
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
withoutRETURNING
, orSELECT ... 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.