Python - basic use of embedded database Sqlite3

SQLite is a lightweight embedded relational database management system, and the Python standard library provides a module for interacting with SQLite, sqlite3. The following is a detailed example and analysis of using the sqlite3 module in Python 3.

import sqlite3  
  
# 创建或连接数据库  
conn = sqlite3.connect('example.db')  
  
# 创建一个游标对象  
cur = conn.cursor()  
  
# 创建表格  
cur.execute('''CREATE TABLE stocks  
             (date text, trans text, symbol text, qty real, price real)''')  
  
# 插入数据  
cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,3.14)")  
  
# 提交更改  
conn.commit()  
  
# 查询数据  
cur.execute("SELECT * FROM stocks")  
rows = cur.fetchall()  
for row in rows:  
    print(row)  
  
# 关闭连接  
conn.close()

This example shows how to use the sqlite3 module to create or connect to a database, create a table, insert some data, query the data, commit the changes and close the connection.

  • First, we connect to a database using the sqlite3.connect() method. If the database does not exist, it will be created. In this example, we are connecting to a database called "example.db".

  • Next, we create a cursor object, which is used to execute SQL statements and return results.

  • We use the cur.execute() method to execute a CREATE TABLE statement to create a table called "stocks". This table has five columns: date, trans, symbol, qty and price.

  • Then, we insert some data into the table using the INSERT INTO statement. In this example, we inserted a row of data including date, transaction type, ticker symbol, quantity and price.

  • Next, we commit our changes using the conn.commit() method. This means our changes will be saved permanently.

  • Then, we execute a SELECT * FROM stocks query using the cur.execute() method. This returns all the data in the table. We fetch all the results using the cur.fetchall() method and print them out using a loop.

  • Finally, we close the connection using the conn.close() method. This frees database resources and ensures our changes have been saved.

This is a very basic example, you can use the sqlite3 module to perform more complex operations such as joining tables, indexes and views etc.

For more detailed or complex operations, you need to learn SQL statements well, write more and practice more.

Guess you like

Origin blog.csdn.net/weixin_44697721/article/details/131964904