2

我的主键声明为:

id bigint PRIMARY KEY

我想提取某个 id,并想进一步使用它。

localid = cursor.fetchone()[0]
print type(localid)
query1 = ("Select * from table_name WHERE id= %d;")
cursor.execute(query1, localid)
query2 = ("Select * from table_name WHERE id= 1;")
cursor.execute(query2)
  1. type(localid)打印为int当前,其中获取的值仅为 2 或 3 或 45。
  2. query1 不起作用,而 query2 起作用。
  3. %d正确的说明符吗?我不这么认为。
  4. 如果获取的数字确实超出了 normal 的范围,int%d吗?如果没有,用什么?

额外信息:使用了 Mysql-python连接器包。蟒蛇 2.7

4

1 回答 1

1

如果你正在使用MySQLdb,你可能只需要%sexecute函数中。

你的Mysql-python确实MySQLdb是。

解决方案1`:

query1 = ("Select * from table_name WHERE id= %s;")
cursor.execute(query1, (localid,))

Note: If args is a sequence, then %s must be used as the
      parameter placeholder in the query. If a mapping is used,
      %(key)s must be used as the placeholder.

解决方案2

query1 = ("Select * from table_name WHERE id= %d;" % localid)
cursor.execute(query1)

详细解释Mysqldb.cursors

class BaseCursor(__builtin__.object)
 |  A base for Cursor classes. Useful attributes:
 |  
 |  description
 |      A tuple of DB API 7-tuples describing the columns in
 |      the last executed query; see PEP-249 for details.
 |  
 |  description_flags
 |      Tuple of column flags for last query, one entry per column
 |      in the result set. Values correspond to those in
 |      MySQLdb.constants.FLAG. See MySQL documentation (C API)
 |      for more information. Non-standard extension.
 |  
 |  arraysize
 |      default number of rows fetchmany() will fetch
 |  
 |  Methods defined here:
 |  execute(self, query, args=None)
 |      Execute a query.
 |      
 |      query -- string, query to execute on server
 |      args -- optional sequence or mapping, parameters to use with query.
 |      
 |      Note: If args is a sequence, then %s must be used as the   #notice
 |      parameter placeholder in the query. If a mapping is used,
 |      %(key)s must be used as the placeholder.
 |      
 |      Returns long integer rows affected, if any
 |
于 2015-08-21T09:29:54.437 回答