MYSQL where clause help!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ronparker
    New Member
    • Aug 2010
    • 27

    MYSQL where clause help!

    Hello, I am using python to run mysql commands, however I don't think that should be a problem. When I am trying to select vales from a mysql talbe, I am having some trouble with the where clause. The vales DATETIME are all integer values around 38947. When I use the actual value 38947 it selects all 26 rows perfectly. however if I use a variable like thedate=38947, and then use the 'thedate' to select the values form the table, I get an error. really any help would be greatly appreciated, THANK YOU!



    Code:
    >>> c.execute('Select REF_LEVERAGE from Actual_Daily_Report Where DATETIME=38947')
    26L
    >>> 
    >>> thedate=38947
    >>> c.execute('Select REF_LEVERAGE from Actual_Daily_Report Where DATETIME=thedate')
    
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 166, in execute
        self.errorhandler(self, exc, value)
      File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
        raise errorclass, errorvalue
    _mysql_exceptions.OperationalError: (1054, "Unknown column 'thedate' in 'where clause'")
  • Jerry Winston
    Recognized Expert New Member
    • Jun 2008
    • 145

    #2
    Everything in side the single quotes gets parsed as sql server query. Turning this line
    Code:
    c.execute('Select REF_LEVERAGE from Actual_Daily_Report Where DATETIME=thedate')
    Into this:
    Code:
    SELECT REF_LEVERAGE FROM Actual_Daily_Report WHERE DATETIME=thedate
    In the second code sample, thedate is viewed as a field name in the context of the overall TSQL query. To make this work. you need to concatenate the query string with the value from your variable. My Python is beyond rusty. You will be better served by members from the Python section.

    Here's my ill-formed attempt at python code:
    Code:
    c.execute('Select REF_LEVERAGE from Actual_Daily_Report Where DATETIME=' + thedate)
    Code:
    c.execute('Select REF_LEVERAGE from Actual_Daily_Report Where DATETIME=' <<myPythonConcatenationOperator>> thedate)

    Comment

    • Oralloy
      Recognized Expert Contributor
      • Jun 2010
      • 988

      #3
      I'm surprised at your representation of DATETIME.

      Why an integer field, and not a native timestamp type field?

      Comment

      Working...