search
HomeBackend DevelopmentPython TutorialAn Introduction to SQLite with Python

An Introduction to SQLite with Python

This article will explore in-depth SQLite database and its use with Python. We will learn how to manipulate SQLite databases through Python's sqlite3 library and finally explore some of the advanced features provided by sqlite3 to simplify our work.

Note: Before you start, it is best to be familiar with SQL. If you are not familiar with it, you can refer to Simply SQL learning.

Core Points

  • SQLite is a lightweight, file-based associated database management system that is commonly used in Python applications because of its simplicity and ease of configuration. It supports concurrent access, allowing multiple processes or threads to access the same database. However, it lacks multi-user capabilities and is not managed as a process like other database technologies such as MySQL or PostgreSQL.
  • The
  • The sqlite3 module in Python provides SQLite with SQLite and is pre-installed with Python. It allows users to create databases, connect to databases, create tables, insert data, and execute SQL commands. The module also supports placeholders, allowing parameter replacement in SQL commands, making it easier to insert variables into queries.
  • Transactions in SQLite are a series of database operations that are treated as a unit to ensure data integrity. Python's sqlite3 module starts a transaction before executing INSERT, UPDATE, DELETE, or REPLACE statements. The user must call the commit() method to save changes made during the transaction and can explicitly handle the transaction by setting isolation_level to None when connecting to the database.

What is SQLite?

SQLite's motto is: "Small, fast, and reliable. Choose two of them."

SQLite is an embedded database library written in C language. You may be familiar with other database technologies, such as MySQL or PostgreSQL. These techniques use the client-server method: the database is installed as a server and then connect to it using the client. SQLite is different: it is called an embedded database because it is included in the program as a library. All data is stored in a file—usually with .db extension—and you can use functions to run SQL statements or do any other action on the database.

File-based storage solutions also provide concurrent access, which means multiple processes or threads can access the same database. So, what is SQLite for? Is it suitable for any type of application?

SQLite performs well in the following situations:

  • Since it is included in most mobile operating systems such as Android and iOS, SQLite may be the perfect choice if you need a standalone, serverless data storage solution.
  • Compared to using large CSV files, you can take advantage of the power of SQL and put all your data into a single SQLite database.
  • SQLite can be used to store configuration data for applications. In fact, SQLite is 35% faster than file-based systems such as configuration files.

On the other hand, what are the reasons why they don’t choose SQLite?

  • Unlike MySQL or PostgreSQL, SQLite lacks multi-user capabilities.
  • SQLite is still a file-based database, not a service. You cannot manage it as a process, nor can you start, stop it, or manage resource usage.

Python's SQLite interface

As I mentioned in the introduction, SQLite is a C library. However, there are many languages ​​that write interfaces, including Python. The sqlite3 module provides an SQL interface and requires at least SQLite 3.7.15.

Amazingly, sqlite3 is available with Python, so you don't need to install anything.

Get to use sqlite3

It's time to write code! In the first part, we will create a basic database. The first thing to do is create a database and connect to it:

import sqlite3
dbName = 'database.db'

try:
  conn = sqlite3.connect(dbName)
  cursor = conn.cursor()
  print("Database created!")

except Exception as e:
  print("Something bad happened: ", e)
  if conn:
    conn.close()

In line 1, we import the sqlite3 library. Then, in a try/except code block, we call sqlite3.connect() to initialize the connection to the database. If everything goes well, conn will be an instance of the Connection object. If try fails, we will print the received exception and close the connection to the database. As stated in the official documentation, each open SQLite database is represented by a Connection object. Every time we have to execute SQL commands, the Connection object has a method called cursor(). In database technology, cursors are a control structure that allows traversing records in a database.

Now, if we execute this code, we should get the following output:

<code>> Database created!</code>

If we look at the folder where the Python script is located, we should see a new file named database.db. This file is automatically created by sqlite3.

Create, read and modify records

At this point, we are ready to create a new table, add the first entry and execute SQL commands such as SELECT, UPDATE, or DROP.

To create a table, we only need to execute a simple SQL statement. In this example, we will create a students table with the following data:

id name surname
1 John Smith
2 Lucy Jacobs
3 Stephan Taylor

After the print("Database created!") line, add the following:

import sqlite3
dbName = 'database.db'

try:
  conn = sqlite3.connect(dbName)
  cursor = conn.cursor()
  print("Database created!")

except Exception as e:
  print("Something bad happened: ", e)
  if conn:
    conn.close()

We create a table and call the cursor.execute() method, which is used when we want to execute a single SQL statement.

Then, we perform an INSERT operation for each row we want to add. After all changes are completed, we call conn.commit() to submit the pending transaction to the database. If the commit() method is not called, any pending changes to the database will be lost. Finally, we close the connection to the database by calling the conn.close() method.

Okay, now let's query our database! We need a variable to hold the result of the query, so let's save the result of cursor.execute() to a variable named records:

<code>> Database created!</code>

After doing this, we will see all records output to standard output:

# 创建操作
create_query = '''CREATE TABLE IF NOT EXISTS student(
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  surname TEXT NOT NULL);
  '''
cursor.execute(create_query)
print("Table created!")

# 插入和读取操作
cursor.execute("INSERT INTO student VALUES (1, 'John', 'Smith')")
print("Insert #1 done!")
cursor.execute("INSERT INTO student VALUES (2, 'Lucy', 'Jacobs')")
print("Insert #2 done!")
cursor.execute("INSERT INTO student VALUES (3, 'Stephan', 'Taylor')")
print("Insert #3 done!")
conn.commit()
conn.close()

At this point, you may have noticed that in the cursor.execute() method, we placed the SQL commands that must be executed. If we want to execute another SQL command (such as UPDATE or DROP), the Python syntax will not change anything.

Placeholder

The

cursor.execute() method requires a string as an argument. In the previous section, we saw how to insert data into our database, but everything is hardcoded. What if we need to store the contents in variables into the database? For this purpose, sqlite3 has some clever features called placeholders. Placeholders allow us to use parameter replacement, which will make it easier to insert variables into queries.

Let's look at this example:

records = cursor.execute("SELECT * FROM student")
for row in records:
  print(row)

We created a method called insert_command(). This method accepts four parameters: the first parameter is an Connection instance, and the other three will be used in our SQL commands.

Each

in the command? variable represents a placeholder. This means that if you call the student_id=1, name='Jason' and surname='Green', the INSERT statement will become insert_command. INSERT INTO student VALUES(1, 'Jason', 'Green')

When we call the

function, we pass our command and all variables that will be replaced with placeholders. From now on, every time we need to insert a row into the execute() table, we will call the student method with the required parameters. insert_command()

Transactions

I will quickly review the importance of it even if you are not new to transaction definition. A transaction is a series of operations performed on a database and is logically considered a unit.

The most important advantage of a transaction is to ensure data integrity. In the example we introduced above, it may not be useful, but the transaction does have an impact when we process more data stored in multiple tables.

Python's sqlite3 module starts a transaction before execute() and executemany() execute INSERT, UPDATE, DELETE, or REPLACE statements. This means two things:

  • We must pay attention to calling the commit() method. If we call commit() without executing Connection.close(), all changes we make during the transaction will be lost.
  • We cannot open transactions with BEGIN in the same process.

Solution? Process transactions explicitly.

How? By using function calls sqlite3.connect(dbName, isolation_level=None) instead of sqlite3.connect(dbName). By setting isolation_level to None, we force sqlite3 to never open the transaction implicitly.

The following code is a rewrite of the previous code, but explicitly uses the transaction:

import sqlite3
dbName = 'database.db'

try:
  conn = sqlite3.connect(dbName)
  cursor = conn.cursor()
  print("Database created!")

except Exception as e:
  print("Something bad happened: ", e)
  if conn:
    conn.close()

Conclusion

I hope you have a good understanding of what SQLite is, how to use it for your Python project, and how some of its advanced features work. Managing transactions explicitly can be a bit tricky at first, but it can certainly help you make the most of it. sqlite3

Related readings:

    Get Started with SQLite3: Basic Commands
  • Begin with Python unit testing using unittest and pytest
  • Manage data in iOS applications using SQLite
  • HTTP Python Request Beginner's Guide
  • SQL and NoSQL: Difference
Frequently Asked Questions about Using SQLite and Python

What is SQLite and why do I use it with Python? SQLite is a lightweight, file-based associated database management system. It is widely used in embedded database applications due to its simplicity and minimal configuration. Using SQLite with Python provides a convenient way to integrate databases into Python applications without the need for a separate database server.

How to connect to SQLite database in Python? You can use the

module (preinstalled with Python) to connect to the SQLite database. Use the sqlite3 method to establish a connection and get the connection object, and then create a cursor to execute the SQL command. connect()

How to create tables in SQLite database using Python? You can run SQL commands using the

method on the cursor object. To create a table, use the execute() statement. CREATE TABLE

How to insert data into SQLite table using Python? Use the

statement to insert data into the table. Placeholders INSERT INTO or %s can be used for parameterized queries to avoid SQL injection. ?

How to use SQLite transactions in Python? Transactions in SQLite are managed using the

and commit() methods on the connection object. Put multiple SQL commands between rollback() and begin to ensure they are treated as a single transaction. commit

The above is the detailed content of An Introduction to SQLite with Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool