Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python的if语句中返回空的变量_Python_Mysql_If Statement_Sql Insert_Connector - Fatal编程技术网

在python的if语句中返回空的变量

在python的if语句中返回空的变量,python,mysql,if-statement,sql-insert,connector,Python,Mysql,If Statement,Sql Insert,Connector,出于某种原因,在if语句中,当调用if not row时,我的title变量始终返回空: 如果变量不在列中,我将尝试插入变量。如果没有返回行,则可能是因为表中没有具有请求的名字的数据。尝试向代码中添加一些调试,并使用参数化查询而不是字符串串联: title = article.title title = re.sub(r' - Wikipedia, the free encyclopedia','',title) title_lower = title.lower() title_lower =

出于某种原因,在if语句中,当调用if not row时,我的title变量始终返回空:


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

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

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
但这种方法存在潜在的竞争条件;如果其他进程在初始检查和后续插入之间向数据库添加值,会怎么样?这可能是问题,也可能不是问题,具体取决于您的应用程序

关于insert if not exists,一种方法是在firstname列上设置唯一索引。然后只需尝试插入一个新行,而无需先进行检查。如果存在与firstname具有相同值的行,则插入将失败。如果不存在这样的行,将尝试插入,但可能仍会失败,但由于其他原因。您的代码需要处理由于重复密钥而导致的插入失败

或者,您可以研究在myguests中使用INSERT IGNORE…,或者此处讨论的其他一些选项:


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

cursor.executeSELECT id FROM myguests,其中firstname='+title+'SQL注入代码的一部分正在工作,但当我到达if语句时,如果返回title变量为空,则它不包含在if之前分配给它的字符串statement@RealConnect:lad2025警告您使用字符串的代码构建SQL语句的连接可能容易受到SQL注入攻击,特别是当数据来自用户时。你能告诉我正确的方向吗?基本上,如果SQL数据库中存在变量dosent,我想更新我的数据库
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,))