Home Backend Development Python Tutorial Detailed explanation of the steps for operating SQLite database in Python

Detailed explanation of the steps for operating SQLite database in Python

Jun 18, 2017 am 11:22 AM
python sqlite about operate database

This article mainly introduces the method of operating SQLite database in Python. It provides a more detailed analysis of Python installation of sqlite database module and common operating techniques for sqlite database. Friends in need can refer to the following

Examples of this article Learn how Python operates SQLite databases. Share it with everyone for your reference, the details are as follows:

A brief introduction to SQLite

##SQLite database is a very compact embedded open source database software , that is to say, there is no independent maintenance process, and all maintenance comes from the program itself. It is a relational database management system that complies with ACID. Its design target is embedded, and it has been used in many embedded products. It occupies very low resources. In embedded devices, it may only require a few One hundred K of memory is enough. It can support mainstream operating systems such as Windows/Linux/Unix, and can be combined with many programming languages, such as Tcl, C#, PHP, Java, etc., as well as ODBC interfaces. It is also compared to the two open source worlds of Mysql and PostgreSQL. In terms of famous database management systems, its processing speed is faster than them all. The first Alpha version of SQLite was born in May 2000. It has been 10 years now, and SQLite has also ushered in a version. SQLite 3 has been released.

Installation and use

1. Import the Python SQLITE database module

After Python2.5 , built-in SQLite3, becomes a built-in module, which saves us the effort of installation, just import it~


import sqlite3
Copy after login

2. Create/open the database

When calling the connect function, specify the library name. If the specified database exists, open the database directly. If it does not exist, create a new one and open it.


cx = sqlite3.connect("E:/test.db")
Copy after login

You can also

Create a database in memory.


con = sqlite3.connect(":memory:")
Copy after login

3. Database connection object

The object cx returned when opening the database is a database connection object, which can have the following Operation:

① commit()--Transaction submission

② rollback()--Transaction rollback
③ close()--Close a database connection
④ cursor()-- Create a cursor

Regarding commit(), if the isolation_level isolation level is default, then this command needs to be used for every operation on the database. You can also set isolation_level=None, which will change to automatic submission mode.

4.Use cursorQuery the database

We need to use the cursor object SQL statement to query the database and obtain the query object. Define a cursor in the following ways.

cu=cx.cursor()

The cursor object has the following operations:

① execute()--Execute sql statement

② executemany--execute multiple sql statements
③ close()--close the cursor
④ fetchone()--take a record from the result and point the cursor to the next record
⑤ fetchmany() --Fetch multiple records from the result
⑥ fetchall()--Fetch all records from the result
⑦ scroll()--Cursor scroll

1. Create table

Copy code The code is as follows:

cu.execute("create table catalog (id

integer primary key,pid integer,name varchar( 10) UNIQUE, nickname text NULL)")

The above statement creates a table called catalog, which has a primary key id, a pid, and a name. The name cannot be repeated, and a nickname defaults is NULL.

2. Insert data

Please be careful to avoid the following writing:


# Never do this -- insecure 会导致注入攻击
pid=200
c.execute("... where pid = '%s'" % pid)
Copy after login

The correct approach is as follows. If t is just a single value, it should also be in the form of t=(n,), because the tuple is immutable.


for t in[(0,10,'abc','Yu'),(1,20,'cba','Xu')]:
  cx.execute("insert into catalog values (?,?,?,?)", t)
Copy after login

Simply insert two rows of data, but you need to be reminded that it will only take effect after it is submitted. We use the database connection object cx to commit and rollback rollback operation.


cx.commit()
Copy after login

3. Query


cu.execute("select * from catalog")
Copy after login

To extract the queried data , use the fetch function of the cursor, such as:


In [10]: cu.fetchall()
Out[10]: [(0, 10, u'abc', u'Yu'), (1, 20, u'cba', u'Xu')]
Copy after login

If we use cu.fetchone(), the first item in the list will be returned first, and if used again, the first item will be returned. Two items, proceed in order.

4. Modify


In [12]: cu.execute("update catalog set name='Boy' where id = 0")
In [13]: cx.commit()
Copy after login

Note, submit after modifying the data

5. Delete


cu.execute("delete from catalog where id = 1") 
cx.commit()
Copy after login

6. Use Chinese

Please confirm your IDE or system default encoding first It is utf-8, and add u


before Chinese

x=u'鱼'
cu.execute("update catalog set name=? where id = 0",x)
cu.execute("select * from catalog")
cu.fetchall()
[(0, 10, u'\u9c7c', u'Yu'), (1, 20, u'cba', u'Xu')]
Copy after login

如果要显示出中文字体,那需要依次打印出每个字符串


In [26]: for item in cu.fetchall():
  ....:   for element in item:
  ....:     print element,
  ....:   print
  ....: 
0 10 鱼 Yu
1 20 cba Xu
Copy after login

7.Row类型

Row提供了基于索引和基于名字大小写敏感的方式来访问列而几乎没有内存开销。 原文如下:

sqlite3.Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.

Row对象的详细介绍

class sqlite3.Row
A Row instance serves as a highly optimized row_factory for Connection objects. It tries to mimic a tuple in most of its features.
It supports mapping access by column name and index, iteration, representation, equality testing and len().
If two Row objects have exactly the same columns and their members are equal, they compare equal.
Changed in version 2.6: Added iteration and equality (hashability).
keys()
This method returns a tuple of column names. Immediately after a query, it is the first member of each tuple in Cursor.description.
New in version 2.6.

下面举例说明


In [30]: cx.row_factory = sqlite3.Row
In [31]: c = cx.cursor()
In [32]: c.execute('select * from catalog')
Out[32]: <sqlite3.Cursor object at 0x05666680>
In [33]: r = c.fetchone()
In [34]: type(r)
Out[34]: <type &#39;sqlite3.Row&#39;>
In [35]: r
Out[35]: <sqlite3.Row object at 0x05348980>
In [36]: print r
(0, 10, u&#39;\u9c7c&#39;, u&#39;Yu&#39;)
In [37]: len(r)
Out[37]: 4
In [39]: r[2]      #使用索引查询
Out[39]: u&#39;\u9c7c&#39;
In [41]: r.keys()
Out[41]: [&#39;id&#39;, &#39;pid&#39;, &#39;name&#39;, &#39;nickname&#39;]
In [42]: for e in r:
  ....:   print e,
  ....: 
0 10 鱼 Yu
Copy after login

使用列的关键词查询


In [43]: r[&#39;id&#39;]
Out[43]: 0
In [44]: r[&#39;name&#39;]
Out[44]: u&#39;\u9c7c&#39;
Copy after login

The above is the detailed content of Detailed explanation of the steps for operating SQLite database in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1234
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

See all articles