PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Databases » Python Update SQLite Table

Python Update SQLite Table

Updated on: March 9, 2021 | 10 Comments

In this lesson, learn to execute an UPDATE Query from a Python application to update the SQLite table’s data. You’ll learn how to use Python’s sqlite3 module to update the SQLite table.

Also Read:

  • Solve Python SQLite Exercise
  • Read Python SQLite Tutorial (Complete Guide)

Table of contents

  • Prerequisites
  • Steps to update a single row of SQLite table
  • Using Python variables in SQLite UPDATE query
  • Update multiple rows of SQLite table using cursor’s executemany()
    • Update multiple Columns of SQLite table
  • Next Steps:

Prerequisites

Before executing the following program, please make sure you know the SQLite table name and its column details.

For this lesson, I am using the ‘SqliteDb_developers’ table present in my SQLite database.

sqlitedb_developers table with data
sqlitedb_developers table with data

If a table is not present in your SQLite database, then please refer to the following articles: –

  • Create SQLite table from Python.
  • Insert data into SQLite Table from Python

Steps to update a single row of SQLite table

As of now, the ‘SqliteDb_developers’ table contains six rows, so let’s update the salary of a developer whose id is 4. To perform SQLite UPDATE query from Python, you need to follow these simple steps:

How to Update SQLite Table in Python

  1. Connect to MySQL from Python

    Refer to Python SQLite database connection to connect to SQLite database from Python using sqlite3 module.

  2. Prepare a SQL Update Query

    Prepare an update statement query with data to update. Mention the column name we want to update and its new value. For example, UPDATE table_name SET column1 = value1, column2 = value2...., columnN = valueN WHERE [condition];

  3. Execute the UPDATE query, using cursor.execute()

    This method executes the operation stored in the UPDATE query.

  4. Commit your changes

    After the successful execution of the SQLite update query, Don’t forget to commit your changes to the database using connection.comit().

  5. Extract the number of rows affected

    After a successful update operation, use a cursor.rowcount method to get the number of rows affected. The count depends on how many rows you are updating.

  6. Verify result using the SQL SELECT query

    Execute a SQLite select query from Python to see the new changes

  7. Close the cursor object and database connection object

    use cursor.clsoe() and connection.clsoe() method to close SQLite connections once the update operation completes.

Example

import sqlite3

def updateSqliteTable():
    try:
        sqliteConnection = sqlite3.connect('SQLite_Python.db')
        cursor = sqliteConnection.cursor()
        print("Connected to SQLite")

        sql_update_query = """Update SqliteDb_developers set salary = 10000 where id = 4"""
        cursor.execute(sql_update_query)
        sqliteConnection.commit()
        print("Record Updated successfully ")
        cursor.close()

    except sqlite3.Error as error:
        print("Failed to update sqlite table", error)
    finally:
        if sqliteConnection:
            sqliteConnection.close()
            print("The SQLite connection is closed")

updateSqliteTable()
Code language: Python (python)

Output

Connected to SQLite Record Updated successfully  The SQLite connection is closed
sqlitedb_developers table after updating the row from Python
sqlitedb_developers table after updating the row from Python

Note: Note: If you are doing multiple update operations and wanted to revert your change in case of failure of any operations, use the rollback() method of a connection class to revert the changes. Use the rollback() method of a connection class. in except block.

Using Python variables in SQLite UPDATE query

Most of the time, we need to update a table with some runtime values. For example, when users update their profile or any other details through a user interface, we need to update a table with those new values. In such cases, It is always best practice to use a parameterized query.

The parameterized query uses placeholders (?) inside SQL statements that contain input from users. It helps us to update runtime values and prevent SQL injection concerns.

import sqlite3

def updateSqliteTable(id, salary):
    try:
        sqliteConnection = sqlite3.connect('SQLite_Python.db')
        cursor = sqliteConnection.cursor()
        print("Connected to SQLite")

        sql_update_query = """Update SqliteDb_developers set salary = ? where id = ?"""
        data = (salary, id)
        cursor.execute(sql_update_query, data)
        sqliteConnection.commit()
        print("Record Updated successfully")
        cursor.close()

    except sqlite3.Error as error:
        print("Failed to update sqlite table", error)
    finally:
        if sqliteConnection:
            sqliteConnection.close()
            print("The sqlite connection is closed")

updateSqliteTable(3, 7500)
Code language: Python (python)

Output

sqlitedb_developers table after updating Python variable using parameterized query
sqlitedb_developers table after updating Python variable using a parameterized query

Let’s understand the above program

  • We used two placeholders in the update query, one for the salary column and the other is for the id column.
  • Next, We prepared a data tuple by specifying two Python variables in sequential order.
  • Next, we passed the SQL update query and data tuple to the cursor.execute() method. Remember variables order in the tuple is sequential as per column placeholders order.

Note: If you have a date column in the SQLite table, and you want to update the Python DateTime variable into a column, then please refer to working with SQLite data time values in Python.

Update multiple rows of SQLite table using cursor’s executemany()

In the above example, we have used execute() method of cursor object to update a single record. But sometimes, we need to update multiple rows of the SQLite table. For example, you want to increase the salary of developers by 20%.

Instead of executing the UPDATE query every time to update each record, you can perform bulk update operations in a single query using the cursor.executemany() method.

The executemany(query, seq_param) method accepts the following two parameters

  • SQL query
  • list of records to be updated.

Now, let see the example. In this example, we are updating three rows.

import sqlite3

def updateMultipleRecords(recordList):
    try:
        sqliteConnection = sqlite3.connect('SQLite_Python.db')
        cursor = sqliteConnection.cursor()
        print("Connected to SQLite")

        sqlite_update_query = """Update SqliteDb_developers set salary = ? where id = ?"""
        cursor.executemany(sqlite_update_query, recordList)
        sqliteConnection.commit()
        print("Total", cursor.rowcount, "Records updated successfully")
        sqliteConnection.commit()
        cursor.close()

    except sqlite3.Error as error:
        print("Failed to update multiple records of sqlite table", error)
    finally:
        if sqliteConnection:
            sqliteConnection.close()
            print("The SQLite connection is closed")

records_to_update = [(9700, 4), (7800, 5), (8400, 6)]
updateMultipleRecords(records_to_update)
Code language: Python (python)

Output:

Connected to SQLite Total 3 Records updated successfully The SQLite connection is closed
sqlitedb_developers table after updating multiple rows from Python
sqlitedb_developers table after updating multiple rows from Python

You can verify the result by selecting data from a SQLite table using Python.

Let’s understand the above example

  • We prepared the SQLite update query with two placeholders (“salary” and “Id” column ) and a list of records to update in tuple format.
  • Each element of a list is nothing but a tuple for each row. Each tuple contains two values, i.e., salary and id of a developer.
  • We passed SQLite update query and record list to executemany() as arguments.
  • To get to know the number of records updated, we used a cursor.rowcount function.

Update multiple Columns of SQLite table

We can also update multiple columns of an SQLite table in a single query. Just prepare a parameterized query using a placeholder to update multiple columns. Let see this with an example program.

import sqlite3

def updateMultipleColumns(id, salary, email):
    try:
        sqliteConnection = sqlite3.connect('SQLite_Python.db')
        cursor = sqliteConnection.cursor()
        print("Connected to SQLite")

        sqlite_update_query = """Update new_developers set salary = ?, email = ? where id = ?"""
        columnValues = (salary, email, id)
        cursor.execute(sqlite_update_query, columnValues)
        sqliteConnection.commit()
        print("Multiple columns updated successfully")
        sqliteConnection.commit()
        cursor.close()

    except sqlite3.Error as error:
        print("Failed to update multiple columns of sqlite table", error)
    finally:
        if sqliteConnection:
            sqliteConnection.close()
            print("sqlite connection is closed")

updateMultipleColumns(3, 6500, 'ben_stokes@gmail.com')
Code language: Python (python)

Output

Connected to SQLite Multiple columns updated successfully sqlite connection is closed
sqlitedb_developers table after updating multiple columns
sqlitedb_developers table after updating multiple columns

Next Steps:

To practice what you learned in this article, Please solve a Python Database Exercise project to Practice and master the Python Database operations.

Filed Under: Python, Python Databases

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Databases

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. ImageGboye says

    August 14, 2022 at 4:08 am

    Please after updating, the changes doesn’t reflect in my database… what can I do?

    Reply
  2. Imagechaminda says

    June 24, 2022 at 10:45 pm

    can we update this table without id. because i dont need update id

    Reply
  3. ImageMax says

    November 21, 2020 at 6:35 pm

    Thanks for great tutorial!

    Having couple questions, why are you commiting twice in the last two examples?
    One is after updating a table I understand, but the next one is after printing message and confusing me, is it nessesary?

    Reply
  4. ImageMarkku says

    August 28, 2020 at 5:52 am

    There seems to be a code misalignment in the updateMultipleColumns() example. The table being updated called “new_developers”,as specified in the “sqlite_update_query”, is not in SQLite_Python.db. I tried the code but changed the table to “SqliteDb_developers” and it works fine.

    (Your SQLite Studio screenshot shows the correct table name)

    These are superb tutorials. I couldn’t ask for better.

    Reply
    • ImageVishal says

      September 1, 2020 at 8:53 am

      Thank you, Markku.

      Reply
  5. Imagekingninja says

    July 5, 2020 at 1:32 pm

    Thanks bro.

    Reply
  6. ImageShagi Dominic says

    June 26, 2020 at 8:20 am

    Thanks for your effort. really appreciated. Your tutorials are simple and to the point. A person without any prior experience in coding and of 55 can simply follow the same. Then you know what I mean…… Thanks a lot.

    Reply
  7. ImageCristian Tacoronte Rivero says

    November 22, 2019 at 10:00 pm

    Hi

    I would like to update a row whose reference is a date with the format dd / mm / yyyy and when using WHERE =? I do not recognize this type of data, however, if I put the same format but without the / if I recognize it. Any option to be able to reference with the format dd / mm / yyyy?

    Greetings and thank you very much for your attention.

    (sorry for my English)

    Reply
  8. ImageNas K says

    November 9, 2019 at 10:39 pm

    Hi Vishal,

    First of all thanks for sharing info on this site.

    I want to update multiple columns in multiple rows, how can we do it?

    I am trying to set up an update routine in python following procedure on this page, I have a SQLite table to update multiple (3) columns and multiple rows (20000-30000) with the values from python list of matching records. The script seems to run OK but does not update values in target table.

    List of records sample as below:

    ['"V1",185687.5,3068437.5,9015526491.0', '"V1",199412.5,3068462.5,9015727587.0', '"V1",199412.5,3068462.5,90157.0', '"V1",185787.5,3068487.5,9015926499.0', '"V1",185787.5,3068487.5,9015926499.0']
    

    Any Idea what am I doing wrong here?

    Reply
    • ImageVishal says

      November 10, 2019 at 11:53 am

      Thank you. Please refer to the section “Python update multiple rows of SQLite table using cursor’s executemany()” of this article.

      You need to pass rows in the l”ist of tuples” format. for example:

      records_to_update = [ ("V1", 185687.5, 3068437.5, 9015526491.0), 
                            ("V1", 199412.5, 3068462.5, 9015727587.0),
      		      ("V1", 199412.5, 3068462.5, 90157.0),
      		      ("V1", 185787.5, 3068487.5, 9015926499.0),
      		      ("V1", 185787.5, 3068487.5, 9015926499.0)	]
      
      Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Databases
TweetF  sharein  shareP  Pin

  Python SQLite

  • Python SQLite Guide
  • Python SQLite Insert
  • Python SQLite Select
  • Python SQLite Update
  • Python SQLite Delete
  • Python SQLite Create Functions
  • Python Parameterized Query
  • Python SQLite BLOB
  • Python SQLite DateTime
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement