PDA

View Full Version : Execute SQL command from Python



Mike
11-07-2011, 10:59 AM
I have a python script that does a number of different things, but one of the first things it needs to do is find a record in a particular SQL (MS SQL) table, and if it has a value in a specific field, to remember that value (python variable), set the value to Null, run the rest of the python, then find that record again and put the value back into that field.

I have an existing script that returns values based on a SQL query (see code below), but in this case I want to actually make changes in SQL based on the query results.


import _mssql as sql

archives = [] #Array for archive tables

conn = sql.connect(server='server', user='user', password='password', database='database') #Connect to SQL

conn.execute_query("SELECT * FROM sys.tables where name like '%[_]H' order by name") #SQL query for listing Archive tables (end in _H)
for row in conn:
...Any ideas on how to do what I want?

Thanks,
Mike.

Mike
11-07-2011, 11:03 AM
I should probably add that my existing script is unrelated :) it just shows how I am currently querying SQL from python

Mike.

MushHead
11-07-2011, 03:29 PM
You need to just execute the SQL UPDATE command.


UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value

Mike
13-07-2011, 08:31 AM
Thanks MushHead - it wasn't the update statement I had issues with, it was the python part. What I needed was a conn.execute_non_query (simple as that) :)

Cheers,
Mike.