使用 Python 和 SQLite 的 SQL


在本文中,我們將學習如何使用 Python 和 SQLite 資料庫來使用 SQL。Python 有一個內建模組可以連線到 SQLite 資料庫。我們將使用 sqlite3 模組來連線 Python 和 SQLite。

我們必須遵循以下步驟來連線 SQLite 資料庫和 Python。請檢視這些步驟並編寫程式。

  • 匯入 sqlite3 模組。
  • 使用 sqlite3.connect(db_name) 方法建立一個連線,該方法將資料庫名稱作為引數。如果不存在,它將建立一個具有給定名稱的檔案;否則,它將開啟具有給定名稱的檔案。
  • 使用 conn.cursor() 從連線中獲取遊標物件。它是 Python 和 SQLite 資料庫之間的中介。我們必須使用此遊標物件來執行 SQL 命令。

以上三個步驟幫助我們與 SQLite 資料庫建立連線。這些步驟與 Python 中的任何資料庫都類似。如果您對以上步驟有任何疑問,請參見下面的程式碼。

# importing the module
import sqlite3

# creating an connection
conn = sqlite3.connect("tutorialspoint.db") # db - database

# Cursor object
cursor = conn.cursor()

現在,我們與資料庫建立了連線。讓我們按照以下步驟使用 SQL 查詢建立資料庫。

  • 編寫 SQL 程式碼以建立具有列名和型別的表。
  • 使用 cursor.execute() 執行程式碼以在資料庫中建立表。
  • 編寫 SQL 程式碼以將一些行插入表中。並像上面那樣執行它們。
  • 使用 conn.commit() 方法提交更改以將其儲存到檔案中。
  • 使用 conn.close() 方法關閉連線。
# importing the module
import sqlite3

# creating an connection
conn = sqlite3.connect("tutorialspoint.db") # db - database

# Cursor object
cursor = conn.cursor()

# code to create a databse table
create_table_sql = """
CREATE TABLE students (
   id INTEGER PRIMARY KEY,
   first_name VARCHAR(20),
   last_name VARCHAR(30),
   gender CHAR(1)
);
"""
# executing the above SQL code
cursor.execute(create_table_sql)

# inserting data into the students table
insert_student_one_sql = """INSERT INTO students VALUES (1, "John", "Hill", "M");"""
cursor.execute(insert_student_one_sql)

insert_student_two_sql = """INSERT INTO students VALUES (2, "Jessy", "Hill", "F");"""
cursor.execute(insert_student_two_sql)

insert_student_three_sql = """INSERT INTO students VALUES (3, "Antony", "Hill", "M");"""
cursor.execute(insert_student_three_sql)

# saving the changes using commit method of connection
conn.commit()

# closing the connection
conn.close()

如果您在執行上述程式碼後沒有收到任何錯誤,那麼您就可以開始了。

如何檢視資料庫表中的資料?讓我們按照給定的步驟編寫程式碼。

  • 連線到資料庫。
  • 建立一個遊標物件。
  • 編寫 SQL 查詢以從表中獲取所需的資料。
  • 現在執行它。
  • 遊標物件將包含您想要的資料。使用 fetchall() 方法獲取它。
  • 透過列印它檢視資料。

如果您有任何疑問,請檢視下面的程式碼。

# importing the module
import sqlite3

# creating an connection
conn = sqlite3.connect("tutorialspoint.db") # db - database

# Cursor object
cursor = conn.cursor()

# SQL query to get all students data
fetch_students_sql = """
SELECT * FROM students;
"""

# executing the SQL query
cursor.execute(fetch_students_sql)

# storing the data in a variable using fetchall() method
students = cursor.fetchall() # a list of tuples

# printing the data
print(students)

如果您執行上述程式,則將獲得與輸出類似的結果。

輸出

[(1, 'John', 'Hill', 'M'), (2, 'Jessy', 'Hill', 'F'), (3, 'Antony', 'Hill', 'M')]

結論

現在,您可以開始在 Python 中使用資料庫了。多加練習才能獲得更多技能。如果您對本教程有任何疑問,請在評論區提出。

更新於:2020年11月13日

瀏覽量 1000+

啟動您的 職業生涯

完成課程獲得認證

開始學習
廣告