0

我正在查询 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:“类型”对象不可下标

4

1 回答 1

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
于 2015-10-07T01:38:09.907 回答