📜  SQLite 数据类型及其对应的Python类型

📅  最后修改于: 2022-05-13 01:54:57.393000             🧑  作者: Mango

SQLite 数据类型及其对应的Python类型

SQLite 是一个基于 C 语言的库,提供可移植和无服务器的 SQL 数据库引擎。它具有基于文件的架构;因此它读取和写入磁盘。由于 SQLite 是零配置数据库,因此在使用前无需安装或设置。从Python 2.5.x 开始,SQLite3 默认带有Python。

在本文中,我们将讨论 SQLite 数据类型及其对应的Python类型

SQLite 中的存储类

一个存储类可以称为相似数据类型的集合。 SQLite 提供以下存储类:

Storage Class

Value Stored



NULL

NULL

INTEGER

Signed Integer (1, 2, 3, 4, 5, or 8 bytes depending on magnitude)

REAL

Floating point value (8 byte IEEE floating-point numbers)

TEXT

TEXT string (encoded in UTF-8, UTF-16BE or UTF-16LE



BLOB (Binary Large Object)

Data stored exactly the way it was input, generally in binary format

术语Storage Class可以与DataType相互使用。

对应的Python数据类型

SQLite 数据类型及其对应的Python类型如下

Storage Class

Python Datatype

NULL

None

INTEGER

int



REAL

float

TEXT

str

BLOB

bytes

在Python可以使用 type()函数来获取参数的类。在下面的程序中,type()函数用于打印我们存储在数据库中的每个值的类。

让我们举一个例子,我们正在创建一个名为 'gfg' 的数据库,然后创建一个名为 exam_hall 的表,其中包含如下一些列:

  1. 姓名(文本),
  2. PIN(整数),
  3. 入住率(真实),
  4. 标志(BLOB)。

然后我们在其中插入一些行并检查在Python中 SQL 查询的帮助下获取的值的数据类型。

Python3
# Python3 program to demonstrate SQLite3 datatypes
# and corresponding Python3 types
  
# import the sqlite3 package
import sqlite3  
  
# create connection to database
cnt = sqlite3.connect('gfg.db')  
  
# Create a exam_hall relation
cnt.execute('''CREATE TABLE exam_hall(
NAME TEXT,
PIN INTEGER,
OCCUPANCY REAL,
LOGO BLOB);''')
  
# Open the logo file in read, binary mode
# read the image as binary data into a variable
fileh = open('/content/JSBinCollaborativeJavaScriptDebugging6-300x160.png', 'rb')
img = fileh.read()
  
# Insert tuples for the relation
cnt.execute('''INSERT INTO exam_hall VALUES(
'centre-a',1125,98.6,?)''', (img,))
cnt.execute('''INSERT INTO exam_hall VALUES(
NULL,1158,80.5,?)''', (img,))
  
# Query the data, print the data and its type
# note: Printing the image binary data is impractical due to its huge size
# instead number of bytes are being printed using len()
cursor = cnt.execute('''SELECT * FROM exam_hall;''')
for i in cursor:
    print(str(i[0])+" "+str(i[1])+" "+str(i[2])+" "+str(len(i[3])))
    print(str(type(i[0]))+" "+str(type(i[1]))+" " +
          str(type(i[2]))+" "+str(type(i[3]))+"\n")


输出:

从该程序的输出中,可以得出以下观察结果:

  1. 作为TEXT插入的 'center-a' 已被Python解释为str
  2. 1125, 1158 插入为INTEGER已被Python解释为int
  3. 98.6、80.5 被插入为REAL已被Python解释为浮点数
  4. NULL被Python解释为NoneType
  5. 以二进制格式作为BLOB插入的徽标图像已被Python解释为bytes