Hướng dẫn python sqlite create table - python sqlite tạo bảng

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 

import sqlite3 as lite
7 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

import sqlite3 as lite
7.

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

import sqlite3 as lite
9.

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

import sqlite3 as lite
9 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

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 ta kết nối CSDL.

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

Để kết nối đến CSDL thì chúng ta 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 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
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)

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

finally:
    
    if con:
        con.close() 

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

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

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 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
path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
3 thì mới thực sự thực thi câu truy vấn lên CSDL).

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ý exception và tự động ngắt kết nối CSDL khi không dùng nữa nếu có từ khóa

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

INSERT

Chúng ta sẽ thực thi câu truy vấn 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 code trên tạo bảng

path = os.path.dirname(__file__) + "\\test.db"
con = lite.connect(path)
5 và insert 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 dùng phương thức

con = None
8 để 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.

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ư UPDATE, DELETE… bạn cũng làm tương tự.

Phương thức executemany()

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 thi 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 insert 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 tuple chứa nhiều tuple khác là các dữ liệu cần truyền vào.

SELECT

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 này cũng rất đơn giản, chỉ cần 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

Chúng ta in các tuple đó ra màn hì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()
4

Bạn cũng có thể in 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à in chúng ra màn hì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()
6

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

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ẽ đẩ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
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 tuple nên bạn có thể truy xuất từng phần tử trong tuple 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

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

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 cần dùng chỉ số nữa.

import sqlite3 as lite
0

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

data = cur.fetchone()
3.

import sqlite3 as lite
1

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

data = cur.fetchone()
5 trong đối tượng Connection 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 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.

import sqlite3 as lite
3

Chúng ta thực thi câu lệnh UPDATE và 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 đối tượng

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

import sqlite3 as lite
6