Python 使用 SQL


在本教程中,我們將學習如何使用**SQLite**資料庫結合SQLPython。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_nameVARCHAR(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",
);"""
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年7月11日

瀏覽量:690

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.