Python2.4- check if there is a MySQL query result or not

134 views Asked by At
cmd_connection1 = ("mysql -uuser -ppw -h127.0.0.1  mydatabase -s"
                   " -N -e \'select * from mytable where ID=\""+ID+"\";\'")

Using Python 2.4, I want to check if there is any result(as a row)

I used :

        if not line1 :
            ...

        if line1 == "Empty" :
             ...

But there is no result.

1

There are 1 answers

1
Fernando Escalante Gon On

A working example I use every day.

Im using mysql connector:

You can download from:

https://dev.mysql.com/downloads/connector/python/

import mysql.connector
# impor mysql connector

cnx = mysql.connector.connect(user='your_user', password='your_pwd', host='you_host',database='your_database')
#create a conecction to mysql server
# change user, password, host and database according your needs

id_a_buscar =15
# i will search this value in my database

cursor = cnx.cursor()
# create a cursor

cursor.execute("""SELECT 

titulo,
clave


FROM

historico

WHERE

libro_pk =%s""", (id_a_buscar,))
# execute a query
# %s stores a variable
# id_a_buscar is assigned to s
# so the REAL query is SELECT titulo, clave FROM historico WHERE libro_pk = 15

resultados = cursor.fetchall()
# store query results in resultados

count = cursor.rowcount
# count how many rows return after the query

if count > 0:
    # if there are records
else:
    # if there are NO records

You should use python 3