Lưu cơ sở dữ liệu sqlite python

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

Đầu tiên chúng ta nhập thư viện sqlite3

import sqlite3

Bây giờ, hãy 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 used a file to doing database

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

VD. Lấy phiên bản 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 data and close con cursor

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

# Close the cursor
cursor.close()

The same is close the connection to database

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

Cuối cùng, chúng ta có đoạn mã 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

Lưu cơ sở dữ liệu sqlite python

Chúng ta kết nối với cơ sở dữ liệu

import sqlite3 as lite
9 và thực hiện câu hỏi 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 mô-đun nhập khẩu

import sqlite3 as lite
7

con = None

Biến

con = None
2 là biến lưu trữ đối tượng
con = None
3 khi chúng tôi kết nối cơ sở dữ liệu

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)

Để kết nối đến cơ sở dữ liệu, chúng ta sử dụng phương thức

con = None
4, phương thức này trả về một đối tượng
con = None
3

cur = con.cursor()    
cur.execute('SELECT SQLITE_VERSION()')

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

con = None
3, chúng ta lấy một đối tượng
con = None
7, đố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 hiện các câu truy vấn. Để thực hiện một câu truy vấn, chúng ta sử dụng phương thức
con = None
8

data = cur.fetchone()

Phương thức

con = None
9 lấy về dòng đầu tiên của bảng dữ liệu trả về

print ("SQLite version: %s" % data)

We ta in data line that ra screen

finally:
    
    if con:
        con.close() 

Sau khi đã hoàn tất công việc, chúng ta sẽ đóng kết nối tới CSDL theo phương thức

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
0

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 ";"
0

Trong ví dụ dưới đây, chúng tôi cũng lấy phiên bản SQLite nhưng sử dụng từ khóa

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
1

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

Sử dụng từ khóa

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
1 có tác dụng làm cho mã dễ dàng 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

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 ";"
2

Python sẽ tự động xử lý ngoại lệ và tự động ngắt kết nối cơ sở dữ liệu khi không sử dụng nữa nếu có từ khóa

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
1

CHÈN

Chúng ta sẽ thực hiện câu hỏi INSERT

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

Đoạn mã trên bảng tạo

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
5 và chèn 8 dòng dữ liệu vào bảng này

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 ";"
4

Bảng

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
5 sẽ có 3 cột là
path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
7,
path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
8 và
path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
9

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

Chúng ta chỉ cần sử dụng phương thức

con = None
8 để thực hiện các câu lệnh SQL. Khi sử dụng từ khóa with, các câu lệnh này sẽ được thực hiện ngay trên cơ sở dữ liệ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 ";"
6

Các câu lệnh như CẬP NHẬT, XÓA… bạn cũng làm tương tự

Phương thức execmany()

Phương thức

cur = con.cursor()    
cur.execute('SELECT SQLITE_VERSION()')
1 tiện lợi hơn bằng cách thực hiện nhiều câu lệnh cùng một lú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 ";"
7

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

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
5

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

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

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
5 đã tồn tại chưa, nếu rồi thì xóa bảng đó và tạo lại bảng mới

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

Chúng ta chèn 8 dòng dữ liệu vào bảng bằng một phương thức duy nhất là

cur = con.cursor()    
cur.execute('SELECT SQLITE_VERSION()')
1, 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 bộ chứa nhiều bộ dữ liệu khác nhau

LỰA CHỌN

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()
0

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

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
5

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

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

con = None
8 với câu SQL tương ứng

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

Phương thức

cur = con.cursor()    
cur.execute('SELECT SQLITE_VERSION()')
7 sẽ trả về một tuple chứa các tuple là các dòng dữ liệu trong bảng

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

We ta in the tuple that ra screen

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

Bạn cũng có thể vào từng dòng một nếu muốn

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úng ta lấy từng dòng và trong màn hình của chúng ta

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()
6

Chúng ta sử 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

con = None
7 đã đọc hết dữ liệu trong bảng

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()
7

Đối tượng

con = None
7 có chứa một con trỏ chỉ đến các dòng trong bảng. Phương thức
con = None
9 sẽ đưa 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
data = cur.fetchone()
1

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()
8

Dữ liệu trả về là một bộ dữ liệu nên bạn có thể truy xuất từng phần tử trong bộ dữ liệu bằng cặp dấu

data = cur.fetchone()
2

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

Get 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

data = cur.fetchone()
3, 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 phải chỉ cần sử dụng

import sqlite3 as lite
0

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

data = cur.fetchone()
3

import sqlite3 as lite
1

To data return is Dictionary thì chúng ta thiết lập thuộc tính

data = cur.fetchone()
5 trong kết nối đối tượng là
data = cur.fetchone()
6

import sqlite3 as lite
2

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

data = cur.fetchone()
3 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 hỏi

Truyền tham số vào câu truy vấn giúp tăng tốc độ thực hiện câu truy vấn và đảm bảo an toàn cho ứng dụng khỏi các kiểu tấn công SQL Injection

import sqlite3 as lite
3

Chúng ta thực hiện câu lệnh UPDATE và sử dụng tham số trong câu lệnh SQL

import sqlite3 as lite
4

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

import sqlite3 as lite
5

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

con = None
7 có thuộc tính
data = cur.fetchone()
9 bao gồm số lượng các dòng dữ liệu vừa được cập nhật