This question already has answers here:
Not sure why my Stored Procedure isn't working between pyodbc and SQL Server (2 answers)
Closed 28 days ago.
I'm currently working with SQL Server and Python to write a small script to execute some queries. The connection to the SQL Server works; I can fetch results from different tables and print them on the terminal.
When I try to select all data from a specific table and write them into a new table it didn't work.
# Import Libs
import re
import pyodbc
from datetime import datetime
# Verbindung mit SQL Datenbank herstellen
conn = pyodbc.connect('DRIVER={SQL Server};'
'SERVER=Censored;'
'DATABASE=1110_Database;'
'UID=Censored;'
'Trusted_Connection=Yes;'
'WSID=Censored;'
'PWD=PASSWORD'
)
cursor = conn.cursor()
# SQL-Abfrage
query = '''
SET NOCOUNT ON
Select Top 10 *
INTO [1110_Database].[dbo].[temp4]
FROM [1110_Database].[dbo].[Table1]
'''
cursor = conn.cursor()
cursor.execute(query)
results = [ ]
for row in cursor:
results.append(row)
cursor.close()
conn.close()
# Print Result in Terminal
print(results)
When I don't print the results at the end and comment the whole results = []
block out, it seems to work but the Table temp4 doesn't exist.
When I use the same SQL Query in SQL Server Management Studio it works.
1条答案
按热度按时间qcuzuvrc1#
Using the
cursor.commit()
before closing the cursor was the answer.