代码如下,顺便说一下,我使用的数据库是teradata,并且在windows 7操作系统和python版本2.7中。
import pyodbc
cnxn = pyodbc.connect('DSN=thisIsAbsolutelyCorrect;UID=cannottellyou;PWD=iamsosorry')
cursor1 = cnxn.cursor()
cursor1=cursor1.execute(
################## OR put your SQL dirctly between here ################
'''
create volatile table table1
(
field1 integer
,field2 integer
)on commit preserve rows;
--insert into table1
--values(12,13);
--select * from table1;
''')
######################### and here ########################
cnxn.commit()
for row in cursor1:
print row
raw_input()
但是我得到的错误是这样的:
Traceback (most recent call last):
File "C:UsersissuserDesktoppytest.py", line 25, in <module>
for row in cursor1:
ProgrammingError: No results. Previous SQL was not a query.
如何解决这个错误?
游标对象将没有需要迭代的行。我认为你需要的是对执行的结果进行迭代。
rows = curs.execute(""" sql code """).fetchall()
for row in rows:
print row
这里是一个模板,可以使用pyodbc从python2.7上传到teradata中的volatile表:
import pyodbc
cnxn = pyodbc.connect('your_connection_string')
curs = cnxn.cursor()
curs.execute("""
CREATE VOLATILE TABLE TABLE_NAME
(
c_0 dec(10,0),
...
c_n dec(10,0)
) PRIMARY INDEX (c0)
ON COMMIT PRESERVE ROWS;
END TRANSACTION;
""")
curs.execute("""
INSERT INTO TABLE_NAME (c_0,...,c_n) VALUES (%s);
"""%value_string)
根据您在Teradata中的设置,您必须显式地结束TRANSACTION。您可以在INSERT周围添加循环,以便逐行上传信息。
您是否考虑过以下几点:
import pyodbc
cnxn = pyodbc.connect('DSN=thisIsAbsolutelyCorrect;UID=cannottellyou;PWD=iamsosorry')
cursor1 = cnxn.cursor()
RowCount=cursor1.execute(
'''
create volatile table table1
(
field1 integer
,field2 integer
)on commit preserve rows;
''').rowcount
RowCount=cursor1.execute('''insert into table1 values(12,13);''').rowcount
cnxn.commit()
for row in cursor1:
print row
raw_input()
我认为问题在于您所编写的EXECUTE()
方法期望返回游标。像INSERT
, UPDATE
, DELETE
这样的DDL和DML语句不返回结果集。在使用ROWCOUNT
变量和EXECUTE()
方法来处理易变表的创建和填充时,您可能会更成功。
您可能还必须在创建volatile表和填充该表之间发出commit。