Latest Post

Tăng thứ hạng và truy cập tự nhiên với 10 phương pháp SEO hay nhất Kiếm Tiền Online (mmo): Khái Niệm và Các Hình Thức Phổ Biến

Trong bài viết trước đó, tôi đã chia sẻ cách kết nối với cơ sở dữ liệu SQLite 3 bằng ngôn ngữ lập trình PHP. Trong phần tiếp theo này, tôi sẽ hướng dẫn các bạn cách thực hiện kết nối tới SQLite một cách dễ dàng nhất bằng ngôn ngữ lập trình Python.

Đầu tiên chúng ta import thư viện sqlite3

import sqlite3

Bây giờ thì thực hiện kết nối đến db, và tạo con trỏ.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect('vinasupport.db')
cursor = sqliteConnection.cursor()
print('DB Init')

Chú ý, SQLite sử dụng một file để làm database.

Sau khi khởi tạo bạn đã có thể thực hiện các câu lệnh SQL

VD: Lấy version của SQLite

# Write a query and execute it with cursor
query = 'select sqlite_version();'
cursor.execute(query)

# Fetch and output result
result = cursor.fetchall()
print('SQLite Version is {}'.format(result))

In dữ liệu và đóng con trỏ

# Fetch and output result
result = cursor.fetchall()
print('SQLite Version is {}'.format(result))

# Close the cursor
cursor.close()

Cuôi cùng là đóng kết nối tới database

if sqliteConnection:
    sqliteConnection.close()
    print('SQLite Connection closed')

Cuối cùng, chúng ta có đoạn code như sau:

import sqlite3

try:
    # Connect to DB and create a cursor
    sqliteConnection = sqlite3.connect('sql.db')
    cursor = sqliteConnection.cursor()
    print('DB Init')

    # Write a query and execute it with cursor
    query = 'select sqlite_version();'
    cursor.execute(query)

    # Fetch and output result
    result = cursor.fetchall()
    print('SQLite Version is {}'.format(result))

    # Close the cursor
    cursor.close()

# Handle errors
except sqlite3.Error as error:
    print('Error occurred - ', error)

# Close DB Connection irrespective of success
# or failure
finally:

    if sqliteConnection:
        sqliteConnection.close()
        print('SQLite Connection closed')

Kết quả sau khi chạy:

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *