Hướng dẫn python connect sqlite3 - python kết nối sqlite3

Trong một bài viết trước mình đã hướng dẫn các bạn kết nối đến SQLite 3 sử dụng ngôn ngữ lập trình PHP. Ở bài viết này, mình sẽ hướng dẫn tiếp các bạn sử dụng ngôn ngữ Python để kết nối đến SQLite một cách đơn giản nhất.

Đầ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:

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 

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
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

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
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

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
5.

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

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
5 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

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
3.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
0

Biến

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
8 là biến lưu trữ đối tượng
if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
9 khi chúng ta kết nối CSDL.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
1

Để kết nối đến CSDL thì chúng ta dùng phương thức

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']
0, phương thức này trả về một đối tượng
if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
9.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
2

Sau khi đã có đối tượng

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
9, chúng ta lấy một đối tượng
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']
3, đố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
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']
4.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
3

Phương thức

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']
5 lấy về dòng đầu tiên của bảng dữ liệu trả về.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
4

Chúng ta in dòng dữ liệu đó ra màn hình.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
5

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

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']
6.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
6

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

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']
7.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
7

Dùng từ khóa

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']
7 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
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']
9 thì mới thực sự thực thi câu truy vấn lên CSDL].

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
8

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

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']
7.

INSERT

Chúng ta sẽ thực thi câu truy vấn INSERT.

# Connect to DB and create a cursor
sqliteConnection = sqlite3.connect['vinasupport.db']
cursor = sqliteConnection.cursor[]
print['DB Init']
9

Đoạn code trên tạo bảng

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 và insert 8 dòng dữ liệu vào bảng này.

# 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]]
0

Bảng

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 sẽ có 3 cột là
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 và
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.

# 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]]
1

Chúng ta chỉ cần dùng phương thức

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']
4 để 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.

# 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]]
2

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

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'
7 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.

# 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]]
3

Chúng ta xóa bảng và tạo lại bảng

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.

# 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]]
4

Đầu tiên chúng ta kiểm tra xem bảng

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 đã tồn tại chưa, nếu rồi thì xóa bảng đó và tạo lại bảng mới.

# 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]]
5

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à

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'
7, 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

# 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]]
6

Chúng ta sẽ lấy các bản ghi từ bảng

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.

# 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]]
7

Việc này cũng rất đơn giản, chỉ cần dùng phương thức

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']
4 với câu SQL tương ứng.

# 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]]
8

Phương thức

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 sẽ trả về một tuple chứa các tuple là các dòng dữ liệu trong bảng.

# 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]]
9

Chúng ta in các tuple đó ra màn hình.

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

# Close the cursor
cursor.close[]
0

Bạn cũng có thể in từng dòng một nếu muốn.

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

# Close the cursor
cursor.close[]
1

Chúng ta lấy từng dòng và in chúng ra màn hình.

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

# Close the cursor
cursor.close[]
2

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

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']
3 đã đọc hết dữ liệu trong bảng.

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

# Close the cursor
cursor.close[]
3

Đối tượng

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']
3 có chứa một con trỏ chỉ đến các dòng trong bảng. Phương thức
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']
5 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
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 ";"
7.

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

# Close the cursor
cursor.close[]
4

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

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 ";"
8.

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

# Close the cursor
cursor.close[]
5

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

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, 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.

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

# Close the cursor
cursor.close[]
6

Trong ví dụ này chúng ta sẽ lấy dữ liệu về dạng

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.

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

# Close the cursor
cursor.close[]
7

Để dữ liệu trả về là Dictionary thì chúng ta thiết lập thuộc tính

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[]
1 trong đối tượng Connection là
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[]
2.

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

# Close the cursor
cursor.close[]
8

Dữ liệu trả về kiểu

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 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.

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

# Close the cursor
cursor.close[]
9

Chúng ta thực thi câu lệnh UPDATE và dùng tham số trong câu lệnh SQL.

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
0

Các tham số trong câu truy vấn được đại diện bằng dấu ?.

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
1

Ngoài ra trong đối tượng

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']
3 có thuộc tính
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 chứa số lượng các dòng dữ liệu vừa được cập nhật.

if sqliteConnection:
    sqliteConnection.close[]
    print['SQLite Connection closed']
2

Bài Viết Liên Quan

Chủ Đề