1

I want to insert a date into Ms-SQL DB. How can I do that?

Here's what I'm doing:-

a = (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")
data =  {'AWB_Number':'1','Weight':'1','Length':'1','Height':'1','Width':'1','Customer_Name':'Naaptol','Scan_Time': a,'Series_Flag':'Others'}

data = (
        data['AWB_Number'], data['Weight'], data['Length'], data['Height'],
        data['Width'], data['Customer_Name'], data['Scan_Time'] ,data['Series_Flag']
        )

print data


con_string = 'DSN=%s;UID=%s;PWD=%s;DATABASE=%s;' % (aramex_dsn, aramex_user, aramex_password, aramex_database)
cnxn = pyodbc.connect(con_string)

cursor = cnxn.cursor()

cursor.execute("insert into data_AutoScale_DELHUB VALUES (%s, %s, %s, %s, %s, %s, %s, %s)" % data)
cnxn.commit()

cnxn.close()

It returns an error saying

Traceback (most recent call last):
  File "tests.py", line 39, in <module>
    cursor.execute("insert into data_AutoScale_DELHUB VALUES (%s, %s, %s, %s, %s, %s, %s, %s)" % data)
pyodbc.ProgrammingError: ('42000', "[42000] [FreeTDS][SQL Server]Incorrect syntax near '09'. (102) (SQLExecDirectW)")

What is the problem?

Following is the Database structure:-

    AWB_Number = models.CharField(max_length = 255)
    Weight = models.CharField(max_length = 255)
    Length = models.CharField(max_length = 255)
    Width = models.CharField(max_length = 255)
    Height = models.CharField(max_length = 255)
    Customer_Name = models.CharField(max_length = 255)
    Scan_Time = models.DateTimeField(db_index = True)
    Series_Flag = models.CharField(max_length = 255)
4
  • Can you give us the real values of data ? Commented Aug 14, 2014 at 9:33
  • I've provided that. Please have a close look at the data Commented Aug 14, 2014 at 9:34
  • I've not the value of 'a' so not all values of 'data' − I think the error is on this value because MS-SQL need a DateTime, so maybe the value is not correctly set. Commented Aug 14, 2014 at 9:50
  • How can I set it right? Commented Aug 14, 2014 at 10:02

2 Answers 2

7

As I saw here, I think for datetime values in database, you must have a datetime.datetime object, not a string. So, just replace

a = (datetime.datetime.now()).strftime("%Y-%m-%d %H:%M:%S")

by

a = datetime.datetime.now()
Sign up to request clarification or add additional context in comments.

9 Comments

Then is any change is required in VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ? %s for datetime needs to be changed to something else or not?
You can do that : cursor.execute("insert into data_AutoScale_DELHUB VALUES (?, ?, ?, ?, ?, ?, ?, ?)", list(data))
I think you should read the documentation of pyodbc if you want to use it correctly, at least the GettingStarted page : code.google.com/p/pyodbc/wiki/GettingStarted
I did cursor.execute("insert into data_AutoScale_DELHUB VALUES (?, ?, ?, ?, ?, ?, ?, ?)", data, but it was throwing TypeError: not all arguments converted during string formatting. Upon Googling, it replaces data with [data] and now it says pyodbc.Error: ('HY000', 'The driver did not supply an error!') . What is the possible outcome of the this?
I set the autocommit to True as well as read on stackoverflow.com/questions/14577757/…. but still the same error.
|
0

For anyone that lands here looking to do this in an MS Access database, you can define the field in your database table as a Date/Time type, and then place your date-time value as a single-quote-delimited string in your INSERT or UPDATE Query.

This string needs to be in a format that Access recognizes as a Date/Time, such as: '2/19/2018 11:44:22 PM' or '02/19/2018 23:44:22'. The ODBC driver takes care of the rest, and the date-time will end up in your table as a valid database Date/Time.

I haven't tried this with MS-SQL, but experience says it should work pretty much the same way. Here's some code that creates the proper format string for MS Access:

import pandas as pd
def MSDate_Format_from_Article(self, datestr: str) -> str:
    # Start with the format: 2018-02-14T21:57:55Z
    try:
        datetime_obj = pd.to_datetime(datestr)
    except:
        log("ERROR: Bad Date!")
        return "01/01/1980 00:00:00"
    else:
        year = "{:04d}".format(datetime_obj.year)
        month = "{:02d}".format(datetime_obj.month)
        day = "{:02d}".format(datetime_obj.day)
        hour ="{:02d}".format(datetime_obj.hour)
        minute = "{:02d}".format(datetime_obj.minute)
        second = "{:02d}".format(datetime_obj.second)
        # Return the date as a string in the format: 02/19/2018 23:44:22
        return month + '/' + day + '/' + year + ' ' + hour + ':' + minute + ':' + second

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.