当前,我成功连接到数据库,然后执行一些sql语句,但是当我尝试检索查询结果时,遇到以下raise ProgrammingError(state,err_text)
pypyodbc.ProgrammingError: ('24000', '[24000] [Microsoft][ODBC SQL Server Driver]Invalid cursor state')
。
这是我的代码:
# Connection to MSSQL
import pypyodbc
connection_live_db = pypyodbc.connect(driver="{SQL Server}", server="xxx.xxx.xxx.xxx", uid="test",
pwd="xxxx", Trusted_Connection="No")
credit_hold_co = connection_live_db.cursor()
# read the sql file in buffer and close
read_sql_file = open('C:\\Users\\userX\\Documents\\Scripts\\credit_hold_co.sql','r')
sql_file = read_sql_file.read()
read_sql_file.close()
# split each sql statement by ;
sqlCommands = sql_file.split(';')
results_sql = ""
# iterate over each command and execute it
for command in sqlCommands:
try:
credit_hold_co.execute(command)
except ValueError:
print(command)
# retrieve results
results = results + str(credit_hold_co.fetchall())
# close sql connection
credit_hold_co.close()
这是我尝试执行的sql命令的示例:
-- credit_hold_co
if OBJECT_ID('tempdb..#Credit_Hold_CO') is not NULL
drop table #Credit_Hold_CO;
create table #Credit_Hold_CO
([co_num] varchar(30),
[credit_hold] char(1),
[credit_hold_reason] char(5),
['Type of credit hold reason'] varchar(20),
[credit_hold_date] datetime );
insert into #Credit_Hold_CO([co_num],[credit_hold],[credit_hold_reason],['Type of credit hold reason'],[credit_hold_date])
select distinct co_num, credit_hold, credit_hold_reason,
(case
when credit_hold_reason = 'PD' then 'Past due payments'
when credit_hold_reason = 'BR' then 'Bankruptcy'
end) as 'Type of credit hold reason',
credit_hold_date
FROM [Database].[dbo].[co] where credit_hold = '1';
select * from #Credit_Hold_CO
order by orig_site;
drop table #Credit_Hold_CO;
我发现了一些与当前问题有关的链接,例如pypyodbc invalid cursor name和SQL statement invalid cursor state 24000,两者都建议创建另一个游标,以避免第一个游标的结果无效,但没有提供更多详细信息。
问题与解答于7月17日@ 13:31 MT更新:
答案 0 :(得分:1)
Alejandro BR和我继续对StackOverflow聊天发表了广泛的评论。经过一番调试后,它有两个方面:
-该文件应该是ANSI编码,或者如果是UTF-8则以这种方式读取:
Storyboard.SetTarget(myRectAnimation, myRectangleGeometry);
-通过以下方式简化Python,使其脱离地面,然后继续循环。每个open("your location","r", encoding="utf-8", errors="replace")
在更新后的查询下方找到:
SELECT
此外,我们必须从txt文件更新sql查询:
# Connection to MSSQL
import pypyodbc
connection_live_db = pypyodbc.connect(driver="{SQL Server}", server="xxx.xxx.xxx.xxx", uid="test",
pwd="xxxx", Trusted_Connection="No")
credit_hold_co = connection_live_db.cursor()
# read the .txt file that contains the query
# Avoid strange characters by saving the file in ANSI
# or use the following code from below if you save in UTF-8
read_sql_file = open('C:\\Users\\userX\\Documents\\Scripts\\credit_hold_co.txt','r', encoding="utf-8", errors="replace")
sql_file = read_sql_file.read()
read_sql_file.close()
# Execute the file that contains the sql query
credit_hold_customer_orders.execute(sql_file)
# store the results in variable
results = credit_hold_customer_orders.fetchall()
# close cursor
credit_hold_customer_orders.close()
print(results)