python - Python2.4-检查是否有MySQL查询结果
问题描述
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" :
...
但是没有结果。
解决方案
我每天都在使用的一个工作示例。
我使用 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
推荐阅读
- mysql - 从服务器接收到的字段“255”的未知字符集索引
- sql - SQL查询计算每个日期的累计行程次数
- r - 添加一个“0”。或字符串中某些数字开头的“0.0”
- openedge - 如何将临时表从过程文件传递到窗口
- r - 在 R 中的 plotly 或 ggplot 中将箭头(或箭头图像)添加到条形图上?
- html - 在跨越一定行数的动态生成的 html 表中浮动图标或 div
- spring - 如何处理 Spring Batch 中的 blob 字段?
- python - 从magnetlink infohash获取元数据
- parsing - 为什么我的解析器生成报告该 LALR(1) 语法不是 LALR(1)?
- java - 在 Java 中哪里设置参数 min.insync.replicas 和 acks?