【问题标题】:variable returning empty in if statement python在if语句python中返回空的变量
【发布时间】:2016-04-02 06:38:10
【问题描述】:
title = article.title
title = re.sub(r' - Wikipedia, the free encyclopedia','',title)
title_lower = title.lower()
title_lower = title_lower.replace(' ','-')
print title
print title_lower
title_query = ("INSERT INTO  myguests "
               "(firstname) "
               "VALUES (%s)")

cursor.execute("SELECT id FROM myguests "
                 "WHERE firstname='"+title+"'")

row = cursor.fetchall()
if row !=[]:
    print "List is not empty"
if not row:
    print "List is empty"
    title_query = title
print title

由于某种原因,在我的 if 语句中,如果不是 row,我的 title 变量在被调用时一直返回为空:

如果列中不存在变量,我正在尝试插入变量。

【问题讨论】:

  • cursor.execute("SELECT id FROM myguests " "WHERE firstname='"+title+"'") SQL 注入
  • 这部分代码正在工作,但是当我到达 if 语句时,如果我返回 title 变量为空,它不包含在 if 语句之前分配给它的字符串
  • @RealConnect:lad2025 警告您,使用字符串连接构建 SQL 语句的代码可能容易受到 SQL 注入攻击,尤其是在数据来自用户的情况下。
  • 你能给我指出正确的方向吗?如果我的sql数据库中存在变量dosent,我想更新我的数据库

标签: python mysql if-statement sql-insert connector


【解决方案1】:

如果没有返回任何行,则可能是因为请求的firstname 的表中没有数据。尝试在代码中添加一些调试,并使用参数化查询而不是字符串连接:

cursor.execute("SELECT id FROM myguests WHERE firstname = %s", (title,))
row = cursor.fetchall()
print 'Got row: {!r}'.format(row)    # some debugging

if row:
    print "Record for {} already exists".format(title)
else:
    print "List is empty, attempting to insert"
    cursor.execute(title_query, (title,))

但这种方法存在潜在的竞争条件;如果其他进程在初始检查和后续插入之间将值添加到数据库中会怎样?根据您的应用程序,这可能是也可能不是问题。

关于“如果不存在则插入”,一种方法是在firstname 列上设置唯一索引。然后简单地尝试插入新行而不先检查。如果存在具有相同 firstname 值的行,则插入将失败。如果不存在这样的行,将尝试插入(它可能仍会失败,但出于其他原因)。您的代码需要处理由于重复键导致的插入失败。

或者您可以调查INSERT IGNORE into myguests ... 的使用,或此处讨论的其他一些选项:How to 'insert if not exists' in MySQL?

但是你真的确定firstname 应该是唯一的吗?在我看来,许多客人可能有相同的名字。

【讨论】:

    猜你喜欢
    • 2020-10-12
    • 2019-04-17
    • 2020-09-12
    • 2018-01-08
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    相关资源
    最近更新 更多