Python có thể đọc tệp .DB không?

Hướng dẫn Python SQLite này nhằm trình bày cách phát triển các ứng dụng cơ sở dữ liệu Python với cơ sở dữ liệu SQLite. Bạn sẽ học cách thực hiện các thao tác cơ sở dữ liệu SQLite từ Python

Như các bạn đã biết, SQLite là một thư viện ngôn ngữ C triển khai công cụ cơ sở dữ liệu SQL tương đối nhanh, không cần máy chủ và độc lập, có độ tin cậy cao. SQLite là công cụ cơ sở dữ liệu được sử dụng phổ biến nhất trong môi trường thử nghiệm [Tham khảo Trang chủ SQLite]

SQLite được tích hợp sẵn với hầu hết các máy tính, thiết bị di động và trình duyệt. Mô-đun sqlite3 chính thức của Python giúp chúng tôi làm việc với cơ sở dữ liệu SQLite

Mô-đun python sqlite3 tuân thủ Đặc tả API cơ sở dữ liệu Python v2. 0 [PEP 249]. PEP 249 cung cấp giao diện SQL được thiết kế để khuyến khích và duy trì sự giống nhau giữa các mô-đun Python được sử dụng để truy cập cơ sở dữ liệu

Hãy xem từng phần ngay bây giờ

Mục lục

Kết nối cơ sở dữ liệu Python SQLite

Phần này cho bạn biết cách kết nối với cơ sở dữ liệu SQLite trong Python bằng mô-đun sqlite3

Sử dụng các bước sau để kết nối với SQLite

Cách kết nối với cơ sở dữ liệu SQLite trong Python

  1. Nhập mô-đun sqlite3

    Câu lệnh

    Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
    7 nhập mô-đun sqlite3 trong chương trình. Sử dụng các lớp và phương thức được định nghĩa trong mô-đun sqlite3, chúng ta có thể giao tiếp với cơ sở dữ liệu SQLite

  2. Sử dụng phương thức connect[]

    Sử dụng phương thức

    Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
    8 của lớp
    Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
    9 với tên cơ sở dữ liệu. Để thiết lập kết nối với SQLite, bạn cần chuyển tên cơ sở dữ liệu bạn muốn kết nối. Nếu bạn chỉ định tên tệp cơ sở dữ liệu đã có trên đĩa, nó sẽ kết nối với nó. Nhưng nếu tệp cơ sở dữ liệu SQLite được chỉ định của bạn không tồn tại, SQLite sẽ tạo cơ sở dữ liệu mới cho bạn.
    Phương thức này trả về Đối tượng kết nối SQLite nếu kết nối thành công.

  3. Sử dụng phương thức con trỏ []

    Sử dụng phương thức

    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    0 của lớp kết nối để tạo đối tượng con trỏ để thực thi lệnh/truy vấn SQLite từ Python

  4. Sử dụng phương thức exec[]

    Các phương thức exec[] chạy truy vấn SQL và trả về kết quả

  5. Trích xuất kết quả bằng cách sử dụng hàm tìm nạp []

    Sử dụng

    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    1 hoặc
    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    2 hoặc
    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    3 để đọc kết quả truy vấn

  6. Đóng con trỏ và các đối tượng kết nối

    sử dụng phương thức

    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    4 và
    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    5 để đóng con trỏ và các kết nối SQLite sau khi công việc của bạn hoàn thành

  7. Bắt ngoại lệ cơ sở dữ liệu nếu có thể xảy ra trong quá trình kết nối này

Mô-đun python sqlite3 hoạt động

Chương trình Python sau đây tạo và kết nối với tệp cơ sở dữ liệu mới “SQLite_Python. db” và in chi tiết phiên bản SQLite

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    cursor = sqliteConnection.cursor[]
    print["Database created and Successfully Connected to SQLite"]

    sqlite_select_Query = "select sqlite_version[];"
    cursor.execute[sqlite_select_Query]
    record = cursor.fetchall[]
    print["SQLite Database Version is: ", record]
    cursor.close[]

except sqlite3.Error as error:
    print["Error while connecting to sqlite", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["The SQLite connection is closed"]

đầu ra

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed

SQLite_Python_db

Các điểm quan trọng khi kết nối với SQLite

  • Đối tượng kết nối không an toàn cho luồng. Mô-đun sqlite3 không cho phép chia sẻ kết nối giữa các luồng. Nếu bạn vẫn cố làm như vậy, bạn sẽ gặp ngoại lệ khi chạy
  • Phương thức
    Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
    8 chấp nhận các đối số khác nhau. Trong ví dụ của chúng tôi, chúng tôi đã chuyển đối số tên cơ sở dữ liệu để kết nối
  • Sử dụng một đối tượng kết nối, chúng ta có thể tạo một đối tượng con trỏ cho phép chúng ta thực thi lệnh/truy vấn SQLite thông qua Python
  • Chúng ta có thể tạo bao nhiêu con trỏ tùy ý từ một đối tượng kết nối. Giống như một đối tượng kết nối, đối tượng con trỏ này cũng không an toàn cho luồng. Mô-đun sqlite3 không cho phép chia sẻ con trỏ giữa các luồng. Nếu bạn vẫn cố làm như vậy, bạn sẽ gặp ngoại lệ khi chạy
  • import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    7. Chúng tôi đã đặt tất cả mã của mình vào khối này để nắm bắt các ngoại lệ và lỗi cơ sở dữ liệu SQLite trong quá trình này
  • Sử dụng lớp
    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    8, chúng tôi có thể xử lý bất kỳ lỗi và ngoại lệ cơ sở dữ liệu nào có thể xảy ra khi làm việc với SQLite từ Python
  • Lớp
    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    8 giúp chúng ta hiểu chi tiết về lỗi. Nó trả về một thông báo lỗi và mã lỗi
  • Bạn nên đóng con trỏ và đối tượng kết nối sau khi công việc của bạn hoàn thành để tránh các sự cố về cơ sở dữ liệu.

Tạo bảng SQLite từ Python

Phần này sẽ học cách tạo bảng trong cơ sở dữ liệu SQLite từ Python. Tạo một câu lệnh bảng là một truy vấn DDL. Hãy xem cách thực thi nó từ Python

Trong ví dụ này, chúng tôi đang tạo một bảng

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
50 bên trong cơ sở dữ liệu
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
51

Các bước tạo bảng trong SQLite từ Python. –

  • Kết nối với SQLite bằng
    Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
    52
  • Chuẩn bị truy vấn tạo bảng
  • Thực hiện truy vấn bằng cách sử dụng
    Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
    53
import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]

đầu ra

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
5

bảng sqlitedb_developers

Kiểu dữ liệu SQLite và các kiểu Python tương ứng

Trước khi thực hiện các thao tác SQLite CRUD từ Python, trước tiên hãy hiểu kiểu dữ liệu SQLite và các kiểu Python tương ứng của chúng, điều này sẽ giúp chúng ta lưu trữ và đọc dữ liệu từ bảng SQLite

Công cụ cơ sở dữ liệu SQLite có nhiều lớp lưu trữ để lưu trữ các giá trị. Mọi giá trị được lưu trữ trong cơ sở dữ liệu SQLite đều có một trong các loại lưu trữ hoặc kiểu dữ liệu sau

Kiểu dữ liệu SQLite

  • VÔ GIÁ TRỊ. – Giá trị là giá trị NULL
  • số nguyên. – Để lưu giá trị số. Số nguyên được lưu trữ trong 1, 2, 3, 4, 6 hoặc 8 byte tùy thuộc vào độ lớn của số
  • THỰC. – Giá trị là một giá trị dấu phẩy động, ví dụ: 3. 14 giá trị của PI
  • CHỮ. – Giá trị là một chuỗi văn bản, giá trị TEXT được lưu trữ bằng mã hóa UTF-8, UTF-16BE hoặc UTF-16LE
  • BÃI. – Giá trị là một khối dữ liệu, tôi. e. , Dữ liệu nhị phân. Nó được sử dụng để lưu trữ hình ảnh và tập tin

Các loại Python sau được chuyển đổi thành SQLite mà không gặp vấn đề gì. Vì vậy, khi bạn sửa đổi hoặc đọc từ bảng SQLite bằng cách thực hiện các thao tác CRUD, hãy nhớ bảng này

Các loại PythonCác loại SQLite
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
54
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
55
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
56
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
57_______158
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
59
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
70
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
71
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
72
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
73Kiểu dữ liệu SQLite và các loại Python tương ứng

Thực hiện thao tác SQLite  CRUD từ Python

Hầu hết thời gian, chúng ta cần thao tác dữ liệu của bảng SQLite từ Python. Để thực hiện các thao tác dữ liệu này, chúng tôi thực hiện các truy vấn DML, tôi. e. , thao tác Chèn, Cập nhật, Xóa SQLite từ Python

Bây giờ, chúng ta đã biết chi tiết về bảng và cột của nó, vì vậy hãy chuyển sang các thao tác thô sơ. Tôi đã tạo một hướng dẫn riêng về từng thao tác để trình bày chi tiết. Hãy xem từng phần ngay bây giờ

  • Chèn dữ liệu vào Bảng SQLite từ Python. Tìm hiểu cách thực thi lệnh INSERT từ Python để chèn bản ghi vào bảng SQLite
  • Đọc dữ liệu của Bảng SQLite từ Python. Tìm hiểu cách thực thi truy vấn SQLite SELECT từ Python để tìm nạp các hàng của bảng. Ngoài ra, tôi sẽ cho bạn biết cách sử dụng các phương thức
    Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
    74,
    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    3 và
    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    2 của lớp con trỏ để tìm nạp các hàng giới hạn từ bảng nhằm nâng cao hiệu suất
  • Cập nhật dữ liệu của bảng SQLite từ Python. Tìm hiểu cách thực hiện truy vấn CẬP NHẬT từ Python để sửa đổi các bản ghi của bảng SQLite
  • Xóa dữ liệu khỏi bảng SQLite khỏi Python. Tìm hiểu cách thực hiện truy vấn DELETE từ Python để xóa các bản ghi khỏi bảng SQLite

Thực thi tệp SQL [tập lệnh] từ Python bằng cách sử dụng
Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
77 của con trỏ

Tập lệnh SQLite tiện dụng cho hầu hết công việc hàng ngày. Tập lệnh SQLite là một tập hợp các lệnh SQL được lưu dưới dạng tệp [ở định dạng

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
78]

Tập lệnh SQLite chứa một hoặc nhiều thao tác SQL mà bạn sẽ thực thi từ dấu nhắc dòng lệnh của mình bất cứ khi nào được yêu cầu

Dưới đây là một số tình huống phổ biến mà chúng ta có thể sử dụng tập lệnh SQLite

  • Sao lưu nhiều cơ sở dữ liệu cùng một lúc
  • So sánh số lượng hàng trong bảng từ hai cơ sở dữ liệu khác nhau với cùng một lược đồ
  • Giữ tất cả các lệnh SQL CREATE TABLE của bạn trong tập lệnh cơ sở dữ liệu. Vì vậy, bạn có thể tạo lược đồ cơ sở dữ liệu trên bất kỳ máy chủ nào

Bạn có thể thực thi tập lệnh của mình từ dòng lệnh SQLite bằng cách sử dụng. đọc lệnh, như thế này

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
7

Đối với ví dụ này, tôi đã tạo một tập lệnh SQLite mẫu sẽ tạo hai bảng

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
7

Bây giờ hãy xem cách thực thi tập lệnh SQLite từ Python

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
8

đầu ra

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
9

Các bảng SQLite được tạo bằng cách thực thi tập lệnh SQL từ Python

Ghi chú. Sau khi kết nối với SQLite, Chúng tôi đọc tất cả nội dung của tệp script SQLite được lưu trữ trên đĩa và sao chép nó vào một biến chuỗi python. Sau đó, chúng tôi đã gọi phương thức

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
79 để thực thi tất cả các câu lệnh SQL trong một lần gọi

Chèn/Truy xuất dữ liệu kỹ thuật số trong SQLite bằng Python

Phần này sẽ cho bạn biết cách chèn hoặc lưu bất kỳ thông tin kỹ thuật số nào như tệp, hình ảnh, video hoặc bài hát dưới dạng dữ liệu BLOB vào bảng SQLite từ Python

Ngoài ra, hãy tìm hiểu cách đọc tệp, hình ảnh, video, bài hát hoặc bất kỳ dữ liệu kỹ thuật số nào được lưu trữ trong SQLite bằng Python

Đọc. Python SQLite BLOB để chèn và truy xuất tệp và hình ảnh

Tạo hoặc xác định lại các hàm SQLite bằng Python

Mô-đun python sqlite3 cung cấp cho chúng ta khả năng tạo và xác định lại các hàm SQL từ bên trong Python. Tôi đã tạo một hướng dẫn riêng để trình bày chi tiết. Vui lòng tham khảo Cách tạo và định nghĩa lại các hàm SQL từ bên trong Python

Đọc. Tạo hoặc xác định lại các hàm SQLite từ bên trong Python

Làm việc với các loại dấu thời gian và ngày SQLite trong Python và ngược lại

Đôi khi chúng ta cần chèn hoặc đọc giá trị ngày hoặc DateTime từ bảng SQLite. Vì vậy, nếu bạn đang làm việc với các giá trị ngày tháng hoặc dấu thời gian, vui lòng đọc cách làm việc với các giá trị Ngày giờ SQLite trong Python

Ngoại lệ cơ sở dữ liệu SQLite

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
70

  • Một lớp con của ngoại lệ. Và bạn có thể bỏ qua hoặc đọc và thực hiện hành động nếu cần

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
71

  • Lớp cơ sở của các ngoại lệ khác trong mô-đun sqlite3. Nó là một lớp con của Ngoại lệ

sqlite3. cơ sở dữ liệulỗi

  • Ngoại lệ này được đưa ra cho các lỗi có liên quan đến cơ sở dữ liệu
  • ví dụ. Nếu bạn thử và mở một tệp dưới dạng cơ sở dữ liệu sqlite3 KHÔNG phải là tệp cơ sở dữ liệu, bạn sẽ nhận được
    import sqlite3
    
    try:
        sqliteConnection = sqlite3.connect['SQLite_Python.db']
        sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                    id INTEGER PRIMARY KEY,
                                    name TEXT NOT NULL,
                                    email text NOT NULL UNIQUE,
                                    joining_date datetime,
                                    salary REAL NOT NULL];'''
    
        cursor = sqliteConnection.cursor[]
        print["Successfully Connected to SQLite"]
        cursor.execute[sqlite_create_table_query]
        sqliteConnection.commit[]
        print["SQLite table created"]
    
        cursor.close[]
    
    except sqlite3.Error as error:
        print["Error while creating a sqlite table", error]
    finally:
        if sqliteConnection:
            sqliteConnection.close[]
            print["sqlite connection is closed"]
    
    72

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
73

  • Lớp con của một cơ sở dữ liệuError. Bạn sẽ nhận được Ngoại lệ này khi tính toàn vẹn quan hệ của cơ sở dữ liệu bị ảnh hưởng, e. g. , kiểm tra khóa ngoại không thành công

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
74

  • Nó cũng là một lớp con của DatabaseError. Ngoại lệ này phát sinh do lỗi lập trình, e. g. , tạo bảng có cùng bảng đã tồn tại, lỗi cú pháp trong truy vấn SQL

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
75

  • Nó cũng là một lớp con của DatabaseError. Lỗi này không nằm trong sự kiểm soát của chúng tôi. Ngoại lệ này được đưa ra cho các lỗi liên quan đến hoạt động của cơ sở dữ liệu
  • ví dụ. vô tình ngắt kết nối, máy chủ ngừng hoạt động, xảy ra thời gian chờ, nguồn dữ liệu gặp sự cố. máy chủ ngừng hoạt động

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
76

  • Bạn sẽ nhận được một ngoại lệ được đưa ra khi API cơ sở dữ liệu được sử dụng không được cơ sở dữ liệu hỗ trợ
  • Ví dụ. gọi phương thức rollback[] trên kết nối không hỗ trợ giao dịch. Gọi cam kết sau khi tạo lệnh bảng

Vì vậy, bạn nên viết tất cả mã hoạt động cơ sở dữ liệu của mình trong khối thử để bạn có thể nắm bắt các ngoại lệ trong khối ngoại trừ nếu có và thực hiện các hành động khắc phục đối với nó

Ví dụ: hãy thử chèn dữ liệu vào một bảng không tồn tại trong cơ sở dữ liệu SQLite và In ngăn xếp ngoại lệ đầy đủ

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
8

đầu ra

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
9

Thay đổi thời gian chờ kết nối SQLite khi kết nối từ Python

Khi nhiều kết nối truy cập cơ sở dữ liệu SQLite và một trong các quy trình thực hiện một số thao tác sửa đổi dữ liệu trên cơ sở dữ liệu, tham số thời gian chờ mà chúng tôi chỉ định trong khi kết nối với cơ sở dữ liệu sẽ xác định khoảng thời gian kết nối sẽ chờ khóa biến mất cho đến khi phát sinh ngoại lệ

Giá trị mặc định cho tham số thời gian chờ là 5. 0 [năm giây]. Bất cứ khi nào bạn kết nối với SQLite từ Python và bạn không nhận được phản hồi trong vòng 5 giây, chương trình của bạn sẽ đưa ra một ngoại lệ. Nhưng nếu bạn gặp phải sự cố hết thời gian chờ kết nối và muốn tăng vấn đề này, bạn có thể thực hiện việc này bằng cách sử dụng đối số hết thời gian chờ của hàm

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
52

Hãy xem cách thay đổi giá trị thời gian chờ kết nối

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
0

đầu ra

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
1

Xác định tổng số thay đổi kể từ khi kết nối cơ sở dữ liệu SQLite được mở

Đối với mục đích kiểm tra hoặc thống kê, hãy sử dụng phương thức 

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
78 của lớp kết nối để tìm số lượng hàng cơ sở dữ liệu được sửa đổi, chèn hoặc xóa kể từ khi kết nối cơ sở dữ liệu được mở

Phương thức

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
79 trả về tổng số hàng cơ sở dữ liệu đã bị ảnh hưởng

Ví dụ

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
2

đầu ra

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
3

Sao lưu cơ sở dữ liệu SQLite từ Python

Sử dụng phương pháp

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
80, bạn có thể sao lưu cơ sở dữ liệu SQLite

Database created and Successfully Connected to SQLite SQLite Database Version is:  [['3.28.0',]] The SQLite connection is closed
4

Hàm này lấy một bản sao lưu của cơ sở dữ liệu SQLite và một bản sao sẽ được ghi vào đối số

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
81, đây phải là một phiên bản Kết nối khác. Theo mặc định hoặc khi
import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
82 là 0 hoặc số nguyên âm, toàn bộ cơ sở dữ liệu được sao chép trong một bước duy nhất;

Đối số

import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
83 chỉ định cơ sở dữ liệu mà bạn muốn sao chép. Đối số
import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
84 xác định số giây để ngủ giữa các lần thử liên tiếp để sao lưu các trang còn lại của cơ sở dữ liệu. Đối số
import sqlite3

try:
    sqliteConnection = sqlite3.connect['SQLite_Python.db']
    sqlite_create_table_query = '''CREATE TABLE SqliteDb_developers [
                                id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                email text NOT NULL UNIQUE,
                                joining_date datetime,
                                salary REAL NOT NULL];'''

    cursor = sqliteConnection.cursor[]
    print["Successfully Connected to SQLite"]
    cursor.execute[sqlite_create_table_query]
    sqliteConnection.commit[]
    print["SQLite table created"]

    cursor.close[]

except sqlite3.Error as error:
    print["Error while creating a sqlite table", error]
finally:
    if sqliteConnection:
        sqliteConnection.close[]
        print["sqlite connection is closed"]
84 có thể được chỉ định dưới dạng số nguyên hoặc giá trị dấu phẩy động

Làm cách nào để đọc DB bằng Python?

Các bước tìm nạp hàng từ bảng cơ sở dữ liệu MySQL .
Kết nối với MySQL từ Python. .
Xác định truy vấn CHỌN SQL. .
Nhận đối tượng con trỏ từ kết nối. .
Thực thi truy vấn SELECT sử dụng phương thức exec[]. .
Trích xuất tất cả các hàng từ một kết quả. .
Lặp lại từng hàng. .
Đóng đối tượng con trỏ và đối tượng kết nối cơ sở dữ liệu

Làm cách nào để đọc SQLite DB bằng Python?

Python và SQL .
nhập sqlite3 # Tạo kết nối SQL tới cơ sở dữ liệu SQLite của chúng tôi con = sqlite3. .
nhập sqlite3 # Tạo kết nối SQL tới cơ sở dữ liệu SQLite của chúng tôi con = sqlite3. .
nhập gấu trúc dưới dạng pd nhập sqlite3 # Đọc kết quả truy vấn sqlite vào DataFrame của gấu trúc con = sqlite3

DB nào sử dụng với Python?

SQLite có lẽ là cơ sở dữ liệu đơn giản nhất để kết nối với ứng dụng Python vì bạn không cần cài đặt bất kỳ mô-đun Python SQL bên ngoài nào để làm như vậy. Theo mặc định, bản cài đặt Python của bạn chứa thư viện Python SQL có tên sqlite3 mà bạn có thể sử dụng để tương tác với cơ sở dữ liệu SQLite.

Làm cách nào để đọc tệp DB bằng gấu trúc?

Gấu trúc đọc từ Cơ sở dữ liệu SQLite .
Tạo kết nối cơ sở dữ liệu
Tạo một đối tượng con trỏ thông qua thực thi lệnh SQL SELECT
Tìm nạp tất cả các bản ghi thông qua con trỏ
Chuyển đổi danh sách bản ghi được trả về thành đối tượng DataFrame của gấu trúc

Chủ Đề