Using pymssql to insert datetime object into SQL Server

18,522

Solution 1

you are trying to insert a string that is not formated as date (datetime.datetime.now(), 20130410, '20130410', GETDATE()) so sql server can't parse date from it...

so try this...

cursor.execute("
    INSERT INTO MyTable
    VALUES(
        1,
        'Having Trouble',
        '" + str(datetime.datetime.now()) + "'
    )
")

Solution 2

You can use this code:

# a tuple with the data to be stored in db
data = (1, 'Having Trouble', datetime.datetime.now())
# perform the query 
cursor.execute("INSERT INTO MyTable VALUES(%s, %s, %s)" % data)

Solution 3

Try this out:

timeStamp = str(datetime.datetime.now())[0:-3]

This time stamp format can be converted by MS SQL SERVER and can be used in pymssql to insert an object of type datetime

Share:
18,522
scharfmn
Author by

scharfmn

Python developer from and based in New York. Currently abroad.

Updated on June 19, 2022

Comments

  • scharfmn
    scharfmn almost 2 years

    How do I insert a datatime object using pymssql? I know that the SQL Server table is expecting a datetime object, let's say in position 3. I've tried all three of these:

    cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', datetime.datetime.now())")
    cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', 20130410)")
    cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', '20130410')")
    cursor.execute("INSERT INTO MyTable VALUES(1, 'Having Trouble', GETDATE())")
    

    and I get the same error each time:

    OperationalError: (241, 'Conversion failed when converting date and/or time from character string.DB-Lib error message 241, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n')
    

    I've scoured the little documentation there is, and searched repeatedly.

    EDIT: Secondary problem was a field-length problem. See the first comment on the accepted answer.

  • Thanasis Petsas
    Thanasis Petsas about 11 years
    tanaydin's solution is right! Here I suggest youa bit more flexible way using tuples to store your data before inserting them to the database.
  • scharfmn
    scharfmn about 11 years
    I understand. Had tried it that way first. Here's what I get (my table is actually expecting two datetimes): sqldata = (2, 'url', 'raw', 'uni', 'text', 'mark', 'auth', 'ttitle', 'wtitle', datetime.datetime.now(), datetime.datetime.now(), 'ctype') and then cursor.execute("INSERT INTO WebContent VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)" % sqldata) which yields ProgrammingError: (102, "Incorrect syntax near '18'.DB-Lib error message 102, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n")
  • scharfmn
    scharfmn about 11 years
    See below. I must have a bug.
  • Thanasis Petsas
    Thanasis Petsas about 11 years
    Is the order of the columns in sqldata variable the same with the one of the WebContent table?? Maybe you need to specify the column names of the table before the VALUES. Some examples can be found here: mysql-python.sourceforge.net/MySQLdb.html
  • Thanasis Petsas
    Thanasis Petsas about 11 years
    What about using MySQLdb module?
  • scharfmn
    scharfmn about 11 years
    I tried on a simple test table (just one string). It worked, and I didn't need to specify the column name, but I'll try. Have to use SQL Server - will MySQLdb work with that?
  • Thanasis Petsas
    Thanasis Petsas about 11 years
    I am sorry, I am not sure about that. Maybe it would be useful to show us some SQL code. Please try to make your example to sqlfiddle.com and send us the URL.
  • scharfmn
    scharfmn about 11 years
    This is it. It was a field length problem. datetime.datetime.now() gives me '2013-04-11 10:08:29.512000'. I tried that in SQL Server Management Studio, and it failed. But '2013-04-11 10:08:29.512' works. So I am doing cursor.execute("INSERT INTO MyTable VALUES(2, 'having trouble', '" + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + "')") and it is working. (Also re: format: it may also want the hyphens explicitly - not sure.) Thank you very much for all your help.
  • scharfmn
    scharfmn about 11 years
    Thank you very much. It was a field length issue. Please see below.
  • Thanasis Petsas
    Thanasis Petsas about 11 years
    Ok! I'm glad I could help!
  • scharfmn
    scharfmn about 10 years
    Strftime is more explicit, it seems to me, but then again this is a field length issue, and your solution speaks to that directly.
  • SHernandez
    SHernandez almost 9 years
    @tanaydin in the answer you said "mysql", shouldn't that be "MS SQL"?
  • SHernandez
    SHernandez almost 9 years
    isnt it safer to always use datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') - the output of str could change somehow and it is not very ecplicit, isnt it just a coincidence it fits?