Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.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 通过游标从mySQL中选择记录将返回一个None对象_Python_Mysql_Database_Python 3.x_Mysql Connector - Fatal编程技术网

Python 通过游标从mySQL中选择记录将返回一个None对象

Python 通过游标从mySQL中选择记录将返回一个None对象,python,mysql,database,python-3.x,mysql-connector,Python,Mysql,Database,Python 3.x,Mysql Connector,我正在使用mysqlconnector用python3.x编写一个脚本。 我现在要做的是检查我的数据库中是否有一条记录,它可能与我现在正在分析的记录重复。 我想出了这样的代码: def fill_data(self, db_name, data): cursor = self.cnx.cursor(buffered=True) isDuplicate = cursor.execute(("SELECT destination FROM {0} WHERE destination

我正在使用mysqlconnector用python3.x编写一个脚本。 我现在要做的是检查我的数据库中是否有一条记录,它可能与我现在正在分析的记录重复。 我想出了这样的代码:

def fill_data(self, db_name, data):
    cursor = self.cnx.cursor(buffered=True)
    isDuplicate = cursor.execute(("SELECT destination FROM {0} WHERE destination = '{1}';")
                                 .format(db_name, data['destination']))

    print(cursor.statement)
    self.commit()
    print(isDuplicate is None)
虽然我还是被复制为无对象。我试图通过cursor.statement检查传递给我的db的语句是什么:结果是,在脚本中,当传递给db时,我没有得到obj,查询工作正常。 我还尝试从db_name中选择COUNT(1),这也给了我不同的结果

我没有主意了:也许你们能帮我一下

更新:

对我有效的解决方案是:

    q = ("SELECT * FROM {0} WHERE destination = %s AND countryCode = %s AND prefix = %s")
.format(db_name)
    cursor.execute(q, (data['destination'], data['country_code'], data['prefix']))
    self.cnx.commit()
    isDoubled = cursor.fetchone()

因此,在一天结束时,所有这些都是关于从光标获取数据的:)

可能问题的原因是您使用
execute()
的方式

尝试进行一些更改并查看打印出的内容:

def fill_data(self, db_name, data):
    cursor = self.cnx.cursor(buffered=True)
    q = 'SELECT count(*) FROM {} WHERE destination = %s'.format(db_name)
    duplicate_count = cursor.execute(q, (data['destination'], )).fetchall()
    print(duplicate_count)
(文章在
psql
上,但核心原则与
mysql
中相同)


更新 如果您仍在接收
“NoneType”对象没有atribute“fetchall”
,则错误可能在此处:

cursor = self.cnx.cursor(buffered=True)

看起来您根本没有创建
光标。如果你发布了一些关于
cnx
创建的代码,我可以看一下。

不幸的是,这没有改变任何事情。更重要的是:我不知道我是否正确理解了您在这里要做的事情,但是您应该在format()方法中传递数据['destination'],而不是db_name。这两种方式(您的或我的参数已更改)都没有更改任何内容,只是现在我得到了AttributeError,因为“非类型”对象没有atribute“fetchall”
。format
按它应该的方式工作-
%s
在这里不使用,它在
execute
方法中使用。你可以做
print(q)
来了解我的意思。我将添加一个很好的文档链接,介绍如何在查询中提供参数以及我对
NoneType
的想法。关于您的更新:我不可能不在该行创建游标,因为我稍后在同一函数中使用同一游标对象向数据库添加条目。我现在失业了,但如果你坚持,我可以在星期一给你看一下姓名的缩写:)这很奇怪。好的,把完整的代码贴出来,我来看看