【问题标题】:python - Insert DateTime field in Ms-Sqlpython - 在 Ms-Sql 中插入 DateTime 字段
【发布时间】:2014-08-14 09:30:17
【问题描述】:

我想在 Ms-SQL DB 中插入一个日期。我该怎么做?

这是我正在做的事情:-

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()

它返回一个错误提示

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)")

有什么问题?

以下是数据库结构:-

    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)

【问题讨论】:

  • 你能告诉我们数据的真正价值吗?
  • 我已经提供了。请仔细查看data
  • 我没有 'a' 的值,所以不是所有的 'data' 值 - 我认为错误在这个值上,因为 MS-SQL 需要一个 DateTime,所以值可能不正确设置。
  • 如何正确设置?

标签: python sql sql-server linux


【解决方案1】:

正如我看到的here,我认为对于数据库中的日期时间值,您必须有一个 datetime.datetime 对象,而不是字符串。 所以,只需替换

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

通过

a = datetime.datetime.now()

【讨论】:

  • 那么VALUES (%s, %s, %s, %s, %s, %s, %s, %s) 是否需要更改? %s 是否需要将日期时间更改为其他内容?
  • 你可以这样做:cursor.execute("insert into data_AutoScale_DELHUB VALUES (?, ?, ?, ?, ?, ?, ?, ?)", list(data))
  • 如果你想正确使用它,我认为你应该阅读 pyodbc 的文档,至少是 GettingStarted 页面:code.google.com/p/pyodbc/wiki/GettingStarted
  • 我做了cursor.execute("insert into data_AutoScale_DELHUB VALUES (?, ?, ?, ?, ?, ?, ?, ?)", data,但它正在抛出TypeError: not all arguments converted during string formatting。谷歌搜索时,它用 [data] 替换 data ,现在它说 pyodbc.Error: ('HY000', 'The driver did not supply an error!') 。这可能的结果是什么?
  • 我将自动提交设置为 True 并在 stackoverflow.com/questions/14577757/… 上阅读。但仍然是同样的错误。
【解决方案2】:

对于希望在 MS Access 数据库中执行此操作的任何人,您可以将数据库表中的字段定义为日期/时间类型,然后将日期时间值放置为单引号分隔的字符串在您的 INSERT 或 UPDATE 查询中。

此字符串必须采用 Access 可识别为日期/时间的格式,例如:“2/19/2018 11:44:22 PM”或“02/19/2018 23:44:22”。 ODBC 驱动程序负责其余的工作,日期时间将作为有效的数据库日期/时间在您的表中结束。

我没有在 MS-SQL 上尝试过这个,但经验表明它应该以几乎相同的方式工作。下面是一些为 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

【讨论】:

    猜你喜欢
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多