我正在创建一个连接到 mysql 的 python 程序。
我需要检查一个表是否包含数字 1 以表明它已成功连接,这是我目前的代码:
xcnx.execute('CREATE TABLE settings(status INT(1) NOT NULL)')
xcnx.execute('INSERT INTO settings(status) VALUES(1)')
cnx.commit()
sqlq = "SELECT * FROM settings WHERE status = '1'"
xcnx.execute(sqlq)
results = xcnx.fetchall()
if results =='1':
print 'yep its connected'
else:
print 'nope not connected'
我错过了什么?我是一个 sql 菜鸟,谢谢你们。
最佳答案
我相信最有效的“它是否存在”查询只是做一个count
:
sqlq = "SELECT COUNT(1) FROM settings WHERE status = '1'"
xcnx.execute(sqlq)
if xcnx.fetchone()[0]:
# exists
您不是要求数据库对字段或行执行任何计数操作,而是要求它在结果产生任何匹配项时返回 1 或 0。这比返回实际记录并计算客户端数量要高效得多,因为它节省了双方的序列化和反序列化以及数据传输。
In [22]: c.execute("select count(1) from settings where status = 1")
Out[22]: 1L # rows
In [23]: c.fetchone()[0]
Out[23]: 1L # count found a match
In [24]: c.execute("select count(1) from settings where status = 2")
Out[24]: 1L # rows
In [25]: c.fetchone()[0]
Out[25]: 0L # count did not find a match
count(*)
将与 count(1)
相同。在您的情况下,因为您正在创建一个新表,它将显示 1 个结果。如果你有 10,000 个匹配项,它就是 10000。但你在测试中只关心它是否不为 0,因此你可以执行 bool 真值测试。
更新
实际上,只使用行数甚至不获取结果会更快:
In [15]: if c.execute("select (1) from settings where status = 1 limit 1"):
print True
True
In [16]: if c.execute("select (1) from settings where status = 10 limit 1"):
print True
In [17]:
这也是 django 的 ORM 执行 queryObject.exists()
的方式。
关于python - 如何使用 Python MySQdb 检查记录是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13373843/