Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Xem thảo luận
Cải thiện bài viết
Lưu bài viết
Đọc
Bàn luận
Trong bài viết này, chúng tôi sẽ thảo luận về cách liệt kê tất cả các bảng trong cơ sở dữ liệu SQLite bằng Python. Ở đây, chúng tôi sẽ sử dụng bảng cơ sở dữ liệu đã được tạo từ SQLite. Chúng tôi cũng sẽ tìm hiểu xử lý ngoại lệ trong quá trình kết nối với cơ sở dữ liệu của chúng tôi.
Cơ sở dữ liệu được sử dụng:
sqliteConnection = sqlite3.connect['SQLite_Retrieving_data.db']
Các bước để tìm nạp tất cả các bảng bằng SQLite3 trong Python
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""
1. Tạo một đối tượng kết nối bằng phương thức Connect [],
cursor = sqliteConnection.cursor[]
2. Đã tạo một truy vấn SQLite mà chúng tôi sẽ tìm kiếm một danh sách tất cả các bảng có trong cơ sở dữ liệu SQLite3.
cursor.execute[sql_query]
3. Sử dụng đối tượng kết nối, chúng tôi đang tạo một đối tượng con trỏ.
print[cursor.fetchall[]]
4. Sử dụng các phương thức Execute [], chúng tôi sẽ thực thi truy vấn SQL ở trên.
Python3
5. Cuối cùng, chúng tôi sẽ in một danh sách tất cả các bảng có trong cơ sở dữ liệu SQLite3.
print[cursor.fetchall[]]4
print[cursor.fetchall[]]5
Dưới đây là việc thực hiện
print[cursor.fetchall[]]6
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'3
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'4
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'5
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'1
print[cursor.fetchall[]]6
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'8
print[cursor.fetchall[]]8
print[cursor.fetchall[]]2
print[cursor.fetchall[]]3
print[cursor.fetchall[]]6
C:\User\PhoCode>sqlite3 test.db SQLite version 3.7.13 2012-06-11 02:05:22 Enter ".help" for instructions Enter SQL statements terminated with a ";"5
print[cursor.fetchall[]]6
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'3
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'4
C:\User\PhoCode>sqlite3 test.db SQLite version 3.7.13 2012-06-11 02:05:22 Enter ".help" for instructions Enter SQL statements terminated with a ";"9
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'1
print[cursor.fetchall[]]6
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'3
import sqlite3 as lite import sys import os con = None try: path = os.path.dirname[__file__] + "\\test.db" con = lite.connect[path] cur = con.cursor[] cur.execute['SELECT SQLITE_VERSION[]'] data = cur.fetchone[] print ["SQLite version: %s" % data] except lite.Error as e: print ["Error %s:" % e.args[0]] sys.exit[1] finally: if con: con.close[]3
print[cursor.fetchall[]]6
print[cursor.fetchall[]]7
print[cursor.fetchall[]]8
print[cursor.fetchall[]]9
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'0
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'1
print[cursor.fetchall[]]6
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'3
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'4
import sqlite3 as lite import sys import os con = None try: path = os.path.dirname[__file__] + "\\test.db" con = lite.connect[path] cur = con.cursor[] cur.execute['SELECT SQLITE_VERSION[]'] data = cur.fetchone[] print ["SQLite version: %s" % data] except lite.Error as e: print ["Error %s:" % e.args[0]] sys.exit[1] finally: if con: con.close[]9
import sqlite3 as lite0
import sqlite3 as lite1
print[cursor.fetchall[]]5
print[cursor.fetchall[]]6
C:\User\PhoCode>sqlite3 test.db SQLite version 3.7.13 2012-06-11 02:05:22 Enter ".help" for instructions Enter SQL statements terminated with a ";"1
print[cursor.fetchall[]]8
C:\User\PhoCode>sqlite3 test.db SQLite version 3.7.13 2012-06-11 02:05:22 Enter ".help" for instructions Enter SQL statements terminated with a ";"3
import sqlite3 as lite import sys import os con = None try: path = os.path.dirname[__file__] + "\\test.db" con = lite.connect[path] cur = con.cursor[] cur.execute['SELECT SQLITE_VERSION[]'] data = cur.fetchone[] print ["SQLite version: %s" % data] except lite.Error as e: print ["Error %s:" % e.args[0]] sys.exit[1] finally: if con: con.close[]4
import sqlite3 as lite import sys import os con = None try: path = os.path.dirname[__file__] + "\\test.db" con = lite.connect[path] cur = con.cursor[] cur.execute['SELECT SQLITE_VERSION[]'] data = cur.fetchone[] print ["SQLite version: %s" % data] except lite.Error as e: print ["Error %s:" % e.args[0]] sys.exit[1] finally: if con: con.close[]5
import sqlite3 as lite6
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'3
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'4
con = None1
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'1
Output:
print[cursor.fetchall[]]6
import sqlite3 as lite4
import sqlite3 as lite5
Trong phần này chúng ta sẽ làm việc với cơ sở dữ liệu SQLite.
Python cung cấp sẵn module
print[cursor.fetchall[]]3 hỗ trợ kết nối và thao tác với CSDL SQLite.
C:\User\PhoCode>python Python 3.5.1 [v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48] [MSC v.1900 32 bit [Intel]] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.8.11'
Chúng ta có thể kiểm tra một số thông tin về module
print[cursor.fetchall[]]3.
Trước khi bắt đầu chúng ta cần có một CSDL để test.
C:\User\PhoCode>sqlite3 test.db SQLite version 3.7.13 2012-06-11 02:05:22 Enter ".help" for instructions Enter SQL statements terminated with a ";"
Chúng ta tạo CSDL
con = None5.
Xem phiên bản SQLite
Trong ví dụ dưới đây chúng ta xem phiên bản CSDL SQLite.
import sqlite3 as lite import sys import os con = None try: path = os.path.dirname[__file__] + "\\test.db" con = lite.connect[path] cur = con.cursor[] cur.execute['SELECT SQLITE_VERSION[]'] data = cur.fetchone[] print ["SQLite version: %s" % data] except lite.Error as e: print ["Error %s:" % e.args[0]] sys.exit[1] finally: if con: con.close[]
Chúng ta kết nối với CSDL
con = None5 và thực thi câu truy vấn lấy thông tin về phiên bản SQLite đang sử dụng.
import sqlite3 as lite
Đầu tiên chúng ta import module
print[cursor.fetchall[]]3.
con = None
Biến
con = None8 là biến lưu trữ đối tượng
con = None9 khi chúng ta kết nối CSDL.
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""0
Để kết nối đến CSDL thì chúng ta dùng phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""00, phương thức này trả về một đối tượng
con = None9.
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""1
Sau khi đã có đối tượng
con = None9, chúng ta lấy một đối tượng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""03, đối tượng này làm nhiệm vụ duyệt qua các bản ghi trong tập dữ liệu được lấy về và thực thi các câu truy vấn. Để thực thi một câu truy vấn thì chúng ta dùng phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""04.
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""2
Phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""05 lấy về dòng đầu tiên của bảng dữ liệu trả về.
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""3
Chúng ta in dòng dữ liệu đó ra màn hình.
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""4
Sau khi đã hoàn tất công việc thì chúng ta đóng kết nối tới CSDL với phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""06.
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""5
Trong ví dụ dưới đây, chúng ta cũng lấy phiên bản SQLite nhưng sử dụng từ khóa
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""07.
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""6
Dùng từ khóa
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""07 có tác dụng làm cho code dễ chịu hơn và các câu lệnh SQL có liên quan đến việc cập nhật dữ liệu như INSERT, UPDATE, DELETE… sẽ tự động được thực thi [nếu không thì bạn phải gọi thêm phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""09 thì mới thực sự thực thi câu truy vấn lên CSDL].
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""7
Python sẽ tự động xử lý exception và tự động ngắt kết nối CSDL khi không dùng nữa nếu có từ khóa
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""07.
INSERT
Chúng ta sẽ thực thi câu truy vấn INSERT.
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""8
Đoạn code trên tạo bảng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""11 và insert 8 dòng dữ liệu vào bảng này.
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""9
Bảng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""11 sẽ có 3 cột là
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""13,
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""14 và
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""15.
cursor = sqliteConnection.cursor[]0
Chúng ta chỉ cần dùng phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""04 để thực thi các câu lệnh SQL. Khi dùng từ khóa with thì các câu lệnh này sẽ được thực thi ngay trên CSDL.
cursor = sqliteConnection.cursor[]1
Các câu lệnh như UPDATE, DELETE… bạn cũng làm tương tự.
Phương thức executemany[]
Phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""17 tiện lợi hơn bằng cách thực thi nhiều câu lệnh cùng một lúc.
cursor = sqliteConnection.cursor[]2
Chúng ta xóa bảng và tạo lại bảng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""11.
cursor = sqliteConnection.cursor[]3
Đầu tiên chúng ta kiểm tra xem bảng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""11 đã tồn tại chưa, nếu rồi thì xóa bảng đó và tạo lại bảng mới.
cursor = sqliteConnection.cursor[]4
Chúng ta insert 8 dòng dữ liệu vào bảng bằng một phương thức duy nhất là
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""17, tham số đầu tiên là một câu lệnh SQL có tham số là các dấu ?, tham số thứ 2 là một tuple chứa nhiều tuple khác là các dữ liệu cần truyền vào.
SELECT
cursor = sqliteConnection.cursor[]5
Chúng ta sẽ lấy các bản ghi từ bảng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""11.
cursor = sqliteConnection.cursor[]6
Việc này cũng rất đơn giản, chỉ cần dùng phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""04 với câu SQL tương ứng.
cursor = sqliteConnection.cursor[]7
Phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""23 sẽ trả về một tuple chứa các tuple là các dòng dữ liệu trong bảng.
cursor = sqliteConnection.cursor[]8
Chúng ta in các tuple đó ra màn hình.
cursor = sqliteConnection.cursor[]9
Bạn cũng có thể in từng dòng một nếu muốn.
cursor.execute[sql_query]0
Chúng ta lấy từng dòng và in chúng ra màn hình.
cursor.execute[sql_query]1
Chúng ta dùng một vòng lặp để lặp qua từng dòng dữ liệu trong bảng. Vòng lặp kết thúc khi đối tượng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""03 đã đọc hết dữ liệu trong bảng.
cursor.execute[sql_query]2
Đối tượng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""03 có chứa một con trỏ chỉ đến các dòng trong bảng. Phương thức
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""05 sẽ đẩy con trỏ này lên một dòng và trả về dữ liệu của dòng đó, nếu con trỏ chỉ qua dòng cuối cùng thì sẽ trả về một đối tượng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""27.
cursor.execute[sql_query]3
Dữ liệu trả về là một tuple nên bạn có thể truy xuất từng phần tử trong tuple bằng cặp dấu
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""28.
cursor.execute[sql_query]4
Lấy phần tử thông qua tên cột
Như các ví dụ trên, dữ liệu trả về là một tuple chứa các tuple, nhưng bạn có thể quy định dữ liệu trả về dạng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""29, bằng cách đó bạn có thể truy cập vào các cột thông qua tên cột chứ không cần dùng chỉ số nữa.
cursor.execute[sql_query]5
Trong ví dụ này chúng ta sẽ lấy dữ liệu về dạng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""29.
cursor.execute[sql_query]6
Để dữ liệu trả về là Dictionary thì chúng ta thiết lập thuộc tính
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""31 trong đối tượng Connection là
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""32.
cursor.execute[sql_query]7
Dữ liệu trả về kiểu
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""29 và bạn có thể truy xuất dữ liệu của các ô thông qua tên cột.
Truyền tham số vào câu truy vấn
Truyền tham số vào câu truy vấn giúp tăng tốc độ thực thi câu truy vấn và đảm bảo an toàn cho ứng dụng khỏi kiểu tấn công SQL Injection.
cursor.execute[sql_query]8
Chúng ta thực thi câu lệnh UPDATE và dùng tham số trong câu lệnh SQL.
cursor.execute[sql_query]9
Các tham số trong câu truy vấn được đại diện bằng dấu ?.
print[cursor.fetchall[]]0
Ngoài ra trong đối tượng
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""03 có thuộc tính
sql_query = """SELECT name FROM sqlite_master WHERE type='table';"""35 chứa số lượng các dòng dữ liệu vừa được cập nhật.
print[cursor.fetchall[]]1