【问题标题】:format specifier for bigint of mysql-pythonmysql-python 的 bigint 格式说明符
【发布时间】:2015-11-15 04:27:24
【问题描述】:

我的主键声明为:

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. 如果获取的数字确实超出了正常int 的范围,那么%d 是否正确?如果没有,用什么?

额外信息:Mysql-python 使用了连接器封装。 Python 2.7

【问题讨论】:

  • 你试过运行这个吗?有用吗?
  • 不,它不起作用。如果我直接使用WHERE id=1;,它确实有效。但如果我使用 %d,它不会。

标签: python mysql types mysql-connector-python


【解决方案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
 |

【讨论】:

  • 好的,谢谢。解决方案 2 奏效了。你能告诉我为什么我在 cursor.execute() 中传递的localid 不起作用吗?
  • 你在用MySQLdb吗?
  • 不,我使用的是 MySQL-Python 连接器包。
猜你喜欢
  • 1970-01-01
  • 2016-02-13
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 2021-11-27
相关资源
最近更新 更多