search
HomeBackend DevelopmentPython TutorialDetailed explanation of the steps for operating SQLite database in Python
Detailed explanation of the steps for operating SQLite database in PythonJun 18, 2017 am 11:22 AM
pythonsqliteaboutoperatedatabase

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

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")

You can also

Create a database in memory.


con = sqlite3.connect(":memory:")

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)

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)

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()

3. Query


cu.execute("select * from catalog")

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')]

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()

Note, submit after modifying the data

5. Delete


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

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')]

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


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

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

使用列的关键词查询


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

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
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
如何使用PHP和SQLite创建用户登录系统如何使用PHP和SQLite创建用户登录系统Jul 28, 2023 pm 09:27 PM

如何使用PHP和SQLite创建用户登录系统在当今互联网时代,用户登录系统是许多网站和应用程序的基本功能之一。本文将介绍如何使用PHP和SQLite创建一个简单而强大的用户登录系统。SQLite是一个嵌入式数据库引擎,它是一个零配置的、服务器端的数据库引擎。PHP是一种流行的服务器端脚本语言,它与SQLite结合使用可以创建出灵活且高效的用户登录系统。通过以

使用PHP和SQLite实现用户权限和访问控制使用PHP和SQLite实现用户权限和访问控制Jul 29, 2023 pm 02:33 PM

使用PHP和SQLite实现用户权限和访问控制在现代的web应用程序中,用户权限和访问控制是非常重要的一部分。通过正确的权限管理,可以确保只有经过授权的用户能够访问特定的页面和功能。在本文中,我们将学习如何使用PHP和SQLite来实现基本的用户权限和访问控制。首先,我们需要创建一个SQLite数据库来存储用户和其权限的信息。下面是简单的用户表和权限表的结构

PHP和SQLite:如何进行数据压缩和加密PHP和SQLite:如何进行数据压缩和加密Jul 29, 2023 am 08:36 AM

PHP和SQLite:如何进行数据压缩和加密在许多Web应用程序中,数据的安全性和存储空间的利用率是非常重要的考虑因素。PHP和SQLite是两个非常广泛使用的工具,本文将介绍如何使用它们来进行数据压缩和加密。SQLite是一种轻量级的嵌入式数据库引擎,它没有独立的服务器进程,而是直接与应用程序进行交互。PHP是一种流行的服务器端脚本语言,被广泛用于构建动态

创建一个简单的博客:使用PHP和SQLite创建一个简单的博客:使用PHP和SQLiteJun 21, 2023 pm 01:23 PM

随着互联网的发展,博客成为越来越多人分享自己生活、知识和想法的平台。如果你也想创建一个自己的博客,那么本文将介绍如何使用PHP和SQLite来创建一个简单的博客。确定需求在开始创建博客之前,我们需要确定自己想要实现的功能。例如:创建博客文章编辑博客文章删除博客文章显示博客文章列表显示博客文章详情用户认证和权限控制安装PHP和SQLite我们需要安装PHP和S

使用PHP和SQLite实现数据图表和可视化使用PHP和SQLite实现数据图表和可视化Jul 28, 2023 pm 01:01 PM

使用PHP和SQLite实现数据图表和可视化概述:随着大数据时代的到来,数据图表和可视化成为了展示和分析数据的重要方式。在本文中,将介绍如何使用PHP和SQLite实现数据图表和可视化的功能。以一个实例为例,展示如何从SQLite数据库中读取数据,并使用常见的数据图表库来展示数据。准备工作:首先,需要确保已经安装了PHP和SQLite数据库。如果没有安装,可

如何使用PHP和SQLite进行数据导入和导出如何使用PHP和SQLite进行数据导入和导出Jul 28, 2023 am 11:43 AM

如何使用PHP和SQLite进行数据导入和导出导入和导出数据是在开发网站或应用程序时常见的任务之一。使用PHP和SQLite,我们可以轻松地将数据从外部文件导入到SQLite数据库中,并从数据库导出数据到外部文件。本文将介绍如何使用PHP和SQLite进行数据导入和导出,并提供相应的代码示例。数据导入首先,我们需要准备一个包含要导入的数据的外部文件。这个文件

PHP和SQLite:如何处理长连接和断线重连PHP和SQLite:如何处理长连接和断线重连Jul 29, 2023 am 09:05 AM

PHP和SQLite:如何处理长连接和断线重连引言:在Web开发中,PHP和SQLite是两个常用的技术。然而,长连接和断线重连是在使用PHP和SQLite时经常遇到的一些问题。本文将介绍如何在PHP中处理长连接和断线重连的问题,并提供一些实例代码,以帮助开发者更好地理解和解决这些问题。一、长连接问题在使用PHP连接SQLite数据库时,长连接(Persis

如何使用PHP和SQLite进行全文搜索和索引策略如何使用PHP和SQLite进行全文搜索和索引策略Jul 29, 2023 pm 08:45 PM

如何使用PHP和SQLite进行全文搜索和索引策略引言:在现代的应用程序开发中,全文搜索功能在许多领域中都是不可或缺的。无论是在博客、新闻网站还是在电子商务平台上,用户都习惯使用关键字进行搜索。因此,为了提高用户体验并提供更好的搜索结果,我们需要使用适当的搜索和索引策略来提供全文搜索功能。在本文中,我们将探讨如何使用PHP和SQLite数据库来实现全文搜索和

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools