Python2.4-检查是否有MySQL查询结果

时间:2018-08-06 14:58:32

标签: python mysql python-2.4

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

使用Python 2.4,我想检查是否有任何结果(连续显示)

我用过:

        if not line1 :
            ...

        if line1 == "Empty" :
             ...

但是没有结果。

1 个答案:

答案 0 :(得分:0)

我每天使用的一个工作示例。

我正在使用mysql连接器:

您可以从以下位置下载:

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

您应该使用python 3