why my query works but the data is not saved?

Question:

I have a small script made in Python which has two functions. The first to send data into a table. The second can read the table.

When I call the function that triggers my insert query, the data is not saved in the database.

When I insert an identical query directly into SQL Server it works fine.

So my script is good and my query is good too. Firewall systems are properly configured.

So why data is not saved ?

The primary key of my table is an IDENTITY column. When I activate my insert function, the IDENTITY column still auto increments while no data is saved.

I give you my script :

enter image description here

Here my SQL Server :

enter image description here

The SQL query for creating my table

enter image description here

I try my best to find a solution, i need your help to understand my problem.

Answers:

After inserting with your cursor you need to commit your inserts with connection.commit()

As qaziqarta pointed out it is best practice to not open a new connection everytime you are trying to insert or read something from the database.

You should initialize your connection once at the beginning and close it after you are done reading/writing.

Answered By: Lukas Kuhn

As a quick fix, add commit after execute:

...
cursor.execute(sql)
cursor.connection.commit()

But I would also advise you to keep as little connections as possible. In your current code you create new connection for each operation.

Answered By: qaziqarta
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.