Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Update statement but using pyodbc

I am using a pyodbc driver to connect to a microsoft access table using SQL. Does anyone know how I go about replacing fields within this table?? I have though about deleting the row and then putting the row back but that would change the primary key due to the autonumber in access.

I have this for inserting into the Progress table:

        cnxn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=C:\\Users\\...............(file location)')
        cursor = cnxn.cursor()
        cursor.execute("insert into Progress(CockpitDrill,Mirrors,MoveOff,TurnLeft) values (?,?,?,?)",cockpit,mirrors,moveOff,turnLeft,)
        cnxn.commit()

So how would I replace these fields. Let's say I wanted to change CockpitDrill from '2' to '3', (They are all strings).

Any help would be greatly appreciated.

like image 771
MrPython Avatar asked Jan 14 '15 21:01

MrPython


People also ask

What is the alternative to pyodbc?

Databricks offers the Databricks SQL Connector for Python as an alternative to pyodbc . The Databricks SQL Connector for Python is easier to set up and use, and has a more robust set of coding constructs, than pyodbc .

Can we use and in UPDATE query?

The SQL AND condition and OR condition can be combined to test for multiple conditions in a SELECT, INSERT, UPDATE, or DELETE statement.


1 Answers

You can execute an UPDATE statement just as you now execute your INSERT:

    cnxn = pyodbc.connect('Driver={Microsoft Access Driver (*.mdb, *.accdb)}; Dbq=C:\\Users\\...............(file location)')
    cursor = cnxn.cursor()
    cursor.execute("UPDATE progress SET CockpitDrill = ? WHERE progress_primarykey = ?", newcockpitdrillvalue, oldprimarykeyvalue)
    cnxn.commit()

Does that help? "progress_primarykey" is the assumed name I've given to the primary key field in your database table. That's supposing you just want to change one record and you know its primary key.

like image 176
SKoczian Avatar answered Sep 20 '22 19:09

SKoczian