0

I'm querying into a SQL server to fetch a DATETIME value. Now I want to insert this value into another table. This is my script:

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

How do I convert this TupleRow into a DATETIME SQL value? Currently I'm getting this error because of type incompatibility:

TypeError: 'type' object is not subscriptable

90abyss
  • 7,037
  • 19
  • 63
  • 94

1 Answers1

1

The fetchone() method does indeed return a row. You can extract the individual columns from the row by their zero-based numeric index like this

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

which produces the following output

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
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418