1. Database Operation steps
With Sqlite3 you need to import the package sqlite3, the database needs to be connected to the database and then the cursor cursor is created.
When the program finishes running, you need to close the cursor before closing the database.
(1) Query operation
The steps for the query operation are: 1. Querying using SQL statements, 2. Reading query results from Fetchall
select
when you execute a statement by using the cursor object, featchall()
you can get the result set. The result set is a list, each element is a tuple, corresponding to a row of records.
The sample code is as follows
ImportSqlite3#Importing PackagesConn=sqlite3.connect ('Sample_database')#Connect to the SQLite databaseCursor=conn.cursor ()#Create a cursorCursor.execute ("Select Employee.firstname,employee.lastname from Employee")#using SQL statements to manipulate a database forRowinchCursor.fetchall ():#read operations from Fetchall Print(Row) cursor.close ()#Close CursorConn.close ()#Close the database
(2) Insert, delete and update operations
The steps are: 1. Querying using SQL statements, 2. Commit operation
ImportSqlite3conn=sqlite3.connect ('Sample_database')#Connect to the SQLite databaseCursor=conn.cursor ()#Create a cursorCursor.execute ('CREATE TABLE User (ID varchar () primary key, name varchar )')#Create a table with SQL statementsCursor.execute ('INSERT into user (ID, name) VALUES (\ ' 1\ ', \ ' michael\ ')')#inserting data into a table with an SQL statementPrint(Cursor.rowcount)#display the inserted functionCursor.close ()#Close CursorConn.commit ()#Commit ActionConn.close ()#Close the database
When executed with a cursor object, the execution result is obtained by the number of rows that are insert
update
delete
affected by the rowcount
return of the statement.
Resources
Using sqlite-Liaoche: https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/ 001388320596292f925f46d56ef4c80a1c9d8e47e2d5711000
Sqlite3 Database Python basic operations