Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/71.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 使用MySQLdb执行方法_Python_Mysql - Fatal编程技术网

Python 使用MySQLdb执行方法

Python 使用MySQLdb执行方法,python,mysql,Python,Mysql,我在将动态变量传递到查询中时遇到一些问题。请不要理会这种拙劣的风格。这就是我试图运行的: > sql = "SELECT COUNT(*) FROM artifacts WHERE " \ > "url = '%s' AND " \ > "source_id = '%s'" > self.db.execute(sql, (url, source_id)) 我得到一个错误: self.db.execute(sql) AttributeError:

我在将动态变量传递到查询中时遇到一些问题。请不要理会这种拙劣的风格。这就是我试图运行的:

> sql = "SELECT COUNT(*) FROM artifacts WHERE " \
>       "url = '%s' AND " \
>       "source_id = '%s'"
> self.db.execute(sql, (url, source_id))
我得到一个错误:

self.db.execute(sql)
AttributeError: execute
就我个人而言,我不明白为什么会抛出属性错误。在《用户指南》中,该示例清楚地传递了一个正确的属性

我一直在关注:


咬嘴唇eug。

为了澄清,self.db属性是连接还是光标。因为您只能在游标上调用execute

如果您遵循以下步骤,那么您可以看到有一个从connection属性创建的游标,该游标包含execute方法

下面是一个小例子:

import MySQLdb

## This is the connection to the database
self.db = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.dbname)

## To query you need a cursor, this is created here
c = self.db.cursor()

## On the cursor you can execute a sql stamement and look at result
rows = c.execute('select count(*) from test_table')

## To look at the result use a fetch method, here there is only one result so:
print rows.fetchone()

为了澄清,self.db属性是一个连接还是一个光标。因为您只能在游标上调用execute

如果您遵循以下步骤,那么您可以看到有一个从connection属性创建的游标,该游标包含execute方法

下面是一个小例子:

import MySQLdb

## This is the connection to the database
self.db = MySQLdb.connect(host=self.host, port=self.port, user=self.user, passwd=self.passwd, db=self.dbname)

## To query you need a cursor, this is created here
c = self.db.cursor()

## On the cursor you can execute a sql stamement and look at result
rows = c.execute('select count(*) from test_table')

## To look at the result use a fetch method, here there is only one result so:
print rows.fetchone()

啊!这开始有意义了。这就是我现在所做的:def db_connect(self):dbhandle=_mysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.dbname)self.db=dbhandle.cursor()-这有意义吗,因为它似乎无法正常工作。无所谓。我使用的是mysql而不是MySQLdb,MySQLdb显然是它的包装器。哦。谢谢啊!这开始有意义了。这就是我现在所做的:def db_connect(self):dbhandle=_mysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.dbname)self.db=dbhandle.cursor()-这有意义吗,因为它似乎无法正常工作。无所谓。我使用的是mysql而不是MySQLdb,MySQLdb显然是它的包装器。哦。谢谢