Search code examples
pythonmysqltypesmysql-connector-python

format specifier for bigint of mysql-python


I have my primary key declared as :

id bigint PRIMARY KEY

I want extract a certain id, and want to use it further.

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) is printed as int currently, where the fetched value is just 2 or 3 or 45.
  2. query1 does not work while query2 does.
  3. Is %d the correct specifier? I don't think so.
  4. If the number fetched is indeed out of range of the normal int, would %d be right? If not, what to use?

Extra Info: Mysql-python connector package used. Python 2.7


Solution

  • If you are using MySQLdb, you only need %s in the execute function maybe.

    Your Mysql-python is MySQLdb indeed.

    solution1`:

    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.
    

    solution2:

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

    Detail explaination in 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
     |