Search code examples
pythonsqlsql-serverazure-sql-databasepyodbc

UPDATE row with ID in Azure SQL table with pyodbc (passing variables)


I am attempting to update an entire row with a specific ID in my azure SQL database using pyodbc. I currently have the below query but know that the syntax is not correct.

 def update_invoice(fullName, invoiceNo, date, address, description, total, invoiceID):
    cursor.execute("UPDATE dbo.customerInvoices (customerName, invoiceNo, invoiceDate, customerAddress, invoiceDescription, invoiceTotal) VALUES(?,?,?,?,?,?,?)", (fullName, invoiceNo, date, address, description, total), "WHERE id=?", (invoiceID))
    cnxn.commit() 

As you can see I am passing multiple variables to the query. The query is in 2 parts:

  1. Specifying the columns and what data to enter
  2. Specifying the row to enter the data into

I have used VALUES(?,?,?,?,?) and WHERE id=? in other queries and it works perfectly well. I am just struggling to combine them in 1 query.

Incase this is useful, here is what my table looks like:


Solution

  • That does not look like an UPDATE statement... not sure where you got it from, anyway, here is one that does what you asked.

    def update_invoice(fullName, invoiceNo, date, address, description, total, invoiceID):
        cursor.execute(
            """\
                UPDATE dbo.customerInvoices 
                SET customerName = ?
                    , invoiceNo = ?
                    , invoiceDate = ?
                    , customerAddress = ?
                    , invoiceDescription = ?
                    , invoiceTotal = ?
                WHERE id = ?;
            """,
            (fullName, invoiceNo, date, address, description, total, invoiceID)
        )
        cnxn.commit()