I want to insert values into a SQL Server table, from Python.
Here is my table in SQL Server:
CREATE TABLE DB.type.[Ref]
(
[Type_Ref] varchar(65),
[ID_match] varchar(65),
[Data] varchar(65)
PRIMARY KEY ([Type_Ref], [ID_match])
)
To insert values from python I wrote this code:
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=????;'
'Database=DB;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
sql = "INSERT INTO DB.Ref (Type_Ref, ID_match, Data) VALUES (?, ?, ?)"
cursor.execute(sql, (DATA[Type_Ref], DATA[ID_match], DATA[Data]))
conn.commit()
cursor.close()
conn.close()
However, when I run Python, I don't see any rows of data in SQL Server...
I noticed my IDE is giving this, after I run the python code above:
Process finished with exit code -1073741819 (0xC0000005)
Solution: I solved this problem by deleting the table in sql-server and create a new one.
I think you are not building your conn object correctly. When I try to match your pattern, I receive a TypeError. Try this instead:
server='server'
database='database'
user='username'
password='secret'
conn = pyodbc.connect(
server=server,
database=database,
user=username,
password=password,
port=1433,
driver='ODBC Driver 17 for SQL Server'
)
The rest of your code looks like it should work fine.
try the following:
Columns = ['Type_Ref', 'ID_match', 'Data']
sql = "INSERT INTO dbo.Ref([Type_Ref], [ID_match], [Data]) VALUES (?,?,?)"
cursor.executemany(sql, DATA[Columns].values.tolist())
conn.commit()
Thaks for the help, I solved this problem by deleting the table in sql-server and create a new one.
User contributions licensed under CC BY-SA 3.0