Python进阶2 - 数据库编程: 使用SQLite进行数据库

2019-06-03  本文已影响0人  小马哥China

操作SQLite数据库

使用python操作数据库的流程:

  1. 通过connect()函数获取到数据库连接对象;
  2. 通过数据库连接对象获取到cursor游标对象;
  3. 使用cursor对象执行sql语句;
  4. 关闭游标对象
  5. 数据库连接对象

0.SQLite的一些全局参数

import sqlite3
print("数据库模块的API版本号: ",sqlite3.apilevel)
print("数据库模块的线程安全等级: ",sqlite3.threadsafety)
print("当前使用的SQL语句参数风格: ",sqlite3.paramstyle)
数据库模块的API版本号:  2.0
数据库模块的线程安全等级:  1
当前使用的SQL语句参数风格:  qmark

1.创建数据表

SQLite支持的数据类型:

  1. interger(整型)
  2. real(浮点数)
  3. text(文本)
  4. blob(大二进制对象)
  5. null(空)

甚至直接忽略数据类型也是可以的

# 1,获取到数据库连接对象Connection
conn = sqlite3.connect('firstdb.db')
print(conn)
# 2,获取Cursor 对象
c = conn.cursor()
print(c)
# 3,执行sql语句
c.execute('''create table user_tb(
    _id integer primary key autoincrement,
    name text,
    pass text,
    gender text)''')
c.execute('''create table order_tb(
    _id integer primary key autoincrement,
    item_name text,
    item_price real,
    item_number real,
    user_id integer,
    foreign key(user_id) references user_tb(_id))''')
# 4,关闭游标
c.close();
# 5,关闭数据连接
conn.close()
<sqlite3.Connection object at 0x000001AF8DE7AF10>
<sqlite3.Cursor object at 0x000001AF8DFE9500>

如何观察创建好的数据库与表,使用SQLite Expert工具

去如下网址下载工具(Personal是免费版)
http://www.sqliteexpert.com/download.html

安装和系统的对应版本,我使用的是64位程序

打开已经存在的数据库firstdb.db,就可以查看上面创建的所有数据库信息了

2.插入数据

2.1 插入一条数据

cursor的execute()方法

参数1: sql语句
    
参数2: 参数
import sqlite3

conn = sqlite3.connect('firstdb.db')
c = conn.cursor()

c.execute('insert into user_tb values(null,?,?,?)',('马云','密码123','male'))
c.execute('insert into order_tb values(null,?,?,?,?)',('外卖','100.00','3',1))

conn.commit()
c.close()
conn.close()

2.2 插入多条数据

cursor的executemany()方法:

参数1: sql语句
    
参数2: 参数组成的元组
import sqlite3
conn = sqlite3.connect('firstdb.db')
cursor = conn.cursor()

cursor.executemany('insert into user_tb values(null,?,?,?)',(
    ('小白','123456','male'),
    ('小菜','123456','male'),
    ('菜鸟','123456','male')
))

conn.commit()
cursor.close()
conn.close()

3.执行查询

3.1 获取一条记录

fetchone()

import sqlite3

conn = sqlite3.connect('firstdb.db')
c = conn.cursor()
c.execute('select * from user_tb')
for col in (c.description):
    print(col[0],end='\t')
while True:
    row = c.fetchone()
    if not row:
        break
    print()
    print(row)
    print(row[1] , '-->' , row[2])
c.close()
conn.close()
_id name    pass    gender  
(1, '马云', '密码123', 'male')
马云 --> 密码123

3.2 获取多条记录

fetchmany(n): n条符合查询条件的记录

fetchall(): 全部查询记录

import sqlite3
conn = sqlite3.connect('firstdb.db')
c = conn.cursor()

c.execute('select * from user_tb')

while True:
    rows = c.fetchmany(1)
    for r in rows:
        print(r)
        print(type(r))
    if not rows:
        break
c.close()
conn.close()
(1, '马云', '密码123', 'male')
<class 'tuple'>

4.事务控制

每天补充中

5.执行SQL脚本

6.创建自定义函数

7.创建聚集函数

上一篇下一篇

猜你喜欢

热点阅读