


Detailed explanation of the steps for operating SQLite database in Python
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")
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
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 (idinteger 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. Please be careful to avoid the following writing:# Never do this -- insecure 会导致注入攻击 pid=200 c.execute("... where pid = '%s'" % pid)
for t in[(0,10,'abc','Yu'),(1,20,'cba','Xu')]: cx.execute("insert into catalog values (?,?,?,?)", t)
cx.commit()
3. Query
cu.execute("select * from catalog")
In [10]: cu.fetchall() Out[10]: [(0, 10, u'abc', u'Yu'), (1, 20, u'cba', u'Xu')]
4. Modify
In [12]: cu.execute("update catalog set name='Boy' where id = 0") In [13]: cx.commit()
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 'sqlite3.Row'> In [35]: r Out[35]: <sqlite3.Row object at 0x05348980> In [36]: print r (0, 10, u'\u9c7c', u'Yu') In [37]: len(r) Out[37]: 4 In [39]: r[2] #使用索引查询 Out[39]: u'\u9c7c' In [41]: r.keys() Out[41]: ['id', 'pid', 'name', 'nickname'] In [42]: for e in r: ....: print e, ....: 0 10 鱼 Yu
使用列的关键词查询
In [43]: r['id'] Out[43]: 0 In [44]: r['name'] Out[44]: u'\u9c7c'
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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.

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 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 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.

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 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.

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 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.
