【问题标题】:Python: Convert TupleRow to a Datetime objectPython:将 TupleRow 转换为 Datetime 对象
【发布时间】:2015-10-06 20:04:20
【问题描述】:

我正在查询 SQL 服务器以获取 DATETIME 值。现在我想将此值插入到另一个表中。这是我的脚本:

cursor2.execute(query1)
items = cursor2.fetchall()
for item in items:
    cursor1.execute(query2, [item[0]])
    c_date = cursor1.fetchone()
    print(type(c_date)) #here type is <class 'pypyodbc.TupleRow.<locals>.Row'>
    if c_date is not None:
        cursor2.execute(query3, [c_date, item[0]])

如何将此 TupleRow 转换为 DATETIME SQL 值?由于类型不兼容,目前我收到此错误:

TypeError: 'type' 对象不可下标

【问题讨论】:

    标签: python datetime pypyodbc


    【解决方案1】:

    fetchone() 方法确实返回一行。您可以像这样通过从零开始的数字索引从行中提取各个列

    import pypyodbc
    connStr = (
        r"Driver={SQL Server Native Client 10.0};"
        r"Server=(local)\SQLEXPRESS;"
        r"Database=myDb;"
        r"Trusted_connection=yes;"
    )
    cnxn = pypyodbc.connect(connStr)
    crsr = cnxn.cursor()
    crsr.execute("SELECT LastName, FirstName, DOB FROM Clients WHERE ID=9")
    row = crsr.fetchone()
    print("row type:")
    print(type(row))
    print("row contents:")
    print(row)
    lastName = row[0]
    firstName = row[1]
    dob = row[2]
    print("dob type:")
    print(type(dob))
    print("dob contents:")
    print(dob)
    crsr.close()
    cnxn.close()
    

    产生以下输出

    row type:
    <class 'pypyodbc.Row'>
    row contents:
    (u'Dub\xe9', u'Homer', datetime.datetime(1954, 7, 21, 0, 0))
    dob type:
    <type 'datetime.datetime'>
    dob contents:
    1954-07-21 00:00:00
    

    【讨论】:

      猜你喜欢
      • 2021-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多