python内置SQLite数据库使用方法
python内置了SQLite数据库通过内置sqlite3模块可以直接访问数据库
SQLite 下载页面-sqlite-tools-win32-x86-3370100.zip--直接解压运行sqlite.exe文件打开SQLite数据库命令行窗口
SQLite的部分交互命令
打开SQLite数据库命令行窗口 命令行sqlite3 sqlite>
.open name.db--若数据库存在则打开,否则创建 .database--显示当前打开的数据库文件 .tables--查看当前数据库中的所有表 .schema tbname--查看表结构信息 .exit--退出交互模式 .help--列出命令的提示信息
SQLite的数据类型
smallint 16位整数 integer 32位整数 decimal(p,s) 小数 p是数字的位数,s是小数位数 float 32位浮点数 double 64位浮点数 char(n) 固定长度字符串,n≤254 varchar(n) 不固定长度字符串,n≤4000 graphic(n) 和char(n)一样,单位是两个字节,n≤127 vargraphic(n) 长度可变且最大长度不能大于4000的双字节字符串 data 日期,包括年、月、日 time 时间,包括时、分、秒 datatime 日期和时间
python内置的sqlite3模块中的对象
>>> import sqlite3 >>> sqlite3.version#常量,返回sqlite3模块的版本号 '2.6.0' >>> sqlite3.sqlite_version#常量,返回sqlite数据库的版本号 '3.8.11' >>> sqlite3.connect#数据库连接对象 <built-in function connect> >>> sqlite3.Cursor#游标对象 <class 'sqlite3.Cursor'> >>> sqlite3.Row#行对象 <class 'sqlite3.Row'> >>> sqlite3.connect(dbname)#函数,连接到数据库,返回connect对象 Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> sqlite3.connect(dbname)#函数,连接到数据库,返回connect对象 NameError: name 'dbname' is not defined >>> dir(sqlite3)#列出sqlite3模块中的常量、函数和对象 ['Binary', 'Cache', 'Connection', 'Cursor', 'DataError', 'DatabaseError', 'Date', 'DateFromTicks', 'Error', 'IntegrityError', 'InterfaceError', 'InternalError', 'NotSupportedError', 'OperationalError', 'OptimizedUnicode', 'PARSE_COLNAMES', 'PARSE_DECLTYPES', 'PrepareProtocol', 'ProgrammingError', 'Row', 'SQLITE_ALTER_TABLE', 'SQLITE_ANALYZE', 'SQLITE_ATTACH', 'SQLITE_CREATE_INDEX', 'SQLITE_CREATE_TABLE', 'SQLITE_CREATE_TEMP_INDEX', 'SQLITE_CREATE_TEMP_TABLE', 'SQLITE_CREATE_TEMP_TRIGGER', 'SQLITE_CREATE_TEMP_VIEW', 'SQLITE_CREATE_TRIGGER', 'SQLITE_CREATE_VIEW', 'SQLITE_DELETE', 'SQLITE_DENY', 'SQLITE_DETACH', 'SQLITE_DROP_INDEX', 'SQLITE_DROP_TABLE', 'SQLITE_DROP_TEMP_INDEX', 'SQLITE_DROP_TEMP_TABLE', 'SQLITE_DROP_TEMP_TRIGGER', 'SQLITE_DROP_TEMP_VIEW', 'SQLITE_DROP_TRIGGER', 'SQLITE_DROP_VIEW', 'SQLITE_IGNORE', 'SQLITE_INSERT', 'SQLITE_OK', 'SQLITE_PRAGMA', 'SQLITE_READ', 'SQLITE_REINDEX', 'SQLITE_SELECT', 'SQLITE_TRANSACTION', 'SQLITE_UPDATE', 'Statement', 'Time', 'TimeFromTicks', 'Timestamp', 'TimestampFromTicks', 'Warning', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'adapt', 'adapters', 'apilevel', 'collections', 'complete_statement', 'connect', 'converters', 'datetime', 'dbapi2', 'enable_callback_tracebacks', 'enable_shared_cache', 'paramstyle', 'register_adapter', 'register_converter', 'sqlite_version', 'sqlite_version_info', 'threadsafety', 'time', 'version', 'version_info'] >>> help(sqlite3.connect)#列出sqlite3模块中的常量、函数和对象 Help on built-in function connect in module _sqlite3: connect(...) connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri]) Opens a connection to the SQLite database file *database*. You can use ":memory:" to open a database connection to a database that resides in RAM instead of on disk.
SQLite 3 的函数
打开SQLite数据库命令行窗口使用select命令运行 sqlite> #算数函数,注意SQLite 3命令无法识别#及其后的备注 sqlite> select abs(-234);#返回绝对值 234 sqlite> select max(1,2,4,5,7);#返回最大值 7 sqlite> select min(1,2,4,5,7);#返回最小值 1 sqlite> select random(*);#返回随机值 -6942185573729877674 sqlite> select round(6.678);#四舍五入 7.0 sqlite> #字符串函数 sqlite> select length("we234rfdd");#返回字符串中的字符个数 9 sqlite> select length("we234r测试fdd"); 11 sqlite> select lower('ABCdef');#大写转小写 abcdef sqlite> select upper('ABCdef');#小写转大写 ABCDEF sqlite> select substr('ABCdef',2,5);#截取子串 BCdef sqlite> select substr('ABCdef',5); ef sqlite> select substr('ABCdef',2); BCdef sqlite> select like(A,B);#确定给定的字符串与指定的模式是否匹配 sqlite> select like('ABCdef','25'); 0 sqlite> select like('ABCdef','qwe'); 0 sqlite> select like('ABCdef','Qwe'); 0 sqlite> select like('3456','123'); 0 sqlite> select like('123','123'); 1 sqlite> select like('3456','1234'); 0 sqlite> #时间、日期函数 sqlite> select date();#产生日期 2022-01-04 sqlite> select time();#产生时间 11:08:53 sqlite> select datetime();#产生日期和时间 2022-01-04 11:09:25
SQL关系数据库语言(简单)
#structured query language结构化查询语言
#SQL命令是通用的关系型数据操作语言,不区分大小写,需要在数据库管理系统中运行
#在SQLite窗口中运行SQL命令时,需要在SQL语句后加英文的分号并按回车键执行
1. 数据表的建立和删除
列名 | 具体说明 | 数据类型 |
---|---|---|
emp_id | 员工编号 | integer |
emp_name | 员工姓名 | varchar(20) |
sex | 性别 | char(2) |
title | 职务 | varchar(20) |
wage | 工资 | float |
den_id | 所在部门编号 | integer |
#创建表 create table <表名>( 列名1 数据类型和长度1 列属性1, 列名2 数据类型和长度2 列属性2, …… 列名n 数据类型和长度n 列属性n, ) create table employee( emp_id integer primary key, emp_name varchar(20) not null, sex char(2) default('男'), title varchar(20), wage float, dep_id integer ) #在SQLite中运行如下,记得语句末尾需要加分号 sqlite> .open test.db; sqlite> create table employee( ...> emp_id integer primary key,#primary key定义此列为主关键字,定义为主键的列可以唯一的识别表中的每条记录 ...> emp_name varchar(20) not null,#not null指定此列不许为空,null表示允许为空,是默认值 ...> sex char(2) default('男'),#default('男')指定此sex列默认值为'男',向表中插入数据时,若不指定此列的值则用默认值 ...> title varchar(20), ...> wage float, ...> dep_id integer ...> ); sqlite> #查看表的结构 sqlite> .schema employee#方法1.schema employee CREATE TABLE employee( emp_id integer primary key, emp_name varchar(20) not null, sex char(2) default('男'), title varchar(20), wage float, dep_id integer ); sqlite> sqlite> select * from sqlite_master where type='table' and name='employee';#方法2select * from sqlite_master where type='table' and name='employee'; table|employee|employee|2|CREATE TABLE employee( emp_id integer primary key, emp_name varchar(20) not null, sex char(2) default('男'), title varchar(20), wage float, dep_id integer ) sqlite> #删除表 sqlite> drop table employee;#drop table <表名>删除表及表的结构、属性、索引 sqlite> .tables sqlite>
2. 向表中添加列
sqlite> alter table employee add column tele varchar(50) not null;#alter table <表名> add column <字段名> [<类型>] sqlite> .schema employee CREATE TABLE employee( emp_id integer primary key, emp_name varchar(20) not null, sex char(2) default('男'), title varchar(20), wage float, dep_id integer , tele varchar(50) not null); sqlite>
3. 向表中插入数据
insert into <表名> (字段名-英文逗号分隔) values (表达式-英文逗号分隔) sqlite> insert into employee (emp_id,emp_name,sex,title,wage,dep_id)values(1132,'李四','男','部门经理',7548.6,11); Error: stepping, NOT NULL constraint failed: employee.tele (19)#有NOT NULL要求的必须写入数据 sqlite> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(1132,'李四','男','部门经理',7548.6,11,110); sqlite> sqlite> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(1177,'李四','男','部门经理',7548.6,11,110) ...> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(1342,'九九','女','部门经理',7548.6,11,110) ...> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(1188,'李四','男','经理',8000.6,41,110) ...> ; Error: in prepare, near "insert": syntax error (1)#不能多个数据同时插入
4. 修改表中的数据
#更新一个表中满足条件的记录,一次可以更新多个字值段,如果省略where子句,则更新全部记录 update <表名> set <字段名1>=<表达式1>,[<字段名2>=<表达式2>…] [where <条件表达式>] sqlite> update employee set wage=12345 where emp_id=1399;#把员工编号为1399的员工工资改为12345 sqlite> sqlite> update employee set wage=wage+5000 where emp_id=1399;#把员工编号为1399的员工工资增加5000 sqlite>
5. 删除数据
delete from <表名> [where <条件表达式>]#如果省略where语句则删除该表中全部记录 sqlite> delete from employee where sex='男';#删除表employee中性别为女的记录- sqlite>
6. 查询数据
select <>|* from <> [join <> on <>] [where <>] [group by <>[having <>]] [order by <> [asc|desc]] #select 说明要查询的字段名,如果是“*”则表示查询表中的所有字段 #from 说明查询的数据来源,如果查询的结果来自多个表则需要通过join选项指明连接条件 #where 说明查询的筛选条件,多个条件之间可以用逻辑运算符and or not 连接 #group by 用于将查询结果按分组字段名分组,having子句必须跟随group by 使用来限定分组必须满足的条件 #order by 子句用来对查询结果进行排序 sqlite> select emp_id,emp_name,wage from employee where wage>6000 and sex='女';#检索工资高于6000的女性雇员的雇员号和姓名信息、工资 1342|九九|7548.6 1399|九九|17345.0 sqlite> sqlite> select * from employee where wage>6000 and sex='女';#检索工资高于6000的女性雇员的所有信息 1342|九九|女|部门经理|7548.6|11|110 1399|九九|女|部门经理|17345.0|11|110 sqlite> #添加信息,复制多行文本再粘贴进去 insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(32,'花花','男','部门经理',7548.6,11,110); insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(22,'二分','女','部门经理',7548.6,11,110); insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(12,'夸克','男','经理',8000.6,41,110); insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(62,'花日','男','部门经理',7548.6,11,110); insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(52,'二该','女','部门经理',7548.6,11,110); insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(42,'发动','男','经理',8000.6,41,110); sqlite> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(32,'花花','男','部门经理',7548.6,11,110); sqlite> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(22,'二分','女','部门经理',7548.6,11,110); sqlite> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(12,'夸克','男','经理',8000.6,41,110); sqlite> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(62,'花日','男','部门经理',7548.6,11,110); sqlite> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(52,'二该','女','部门经理',7548.6,11,110); sqlite> insert into employee (emp_id,emp_name,sex,title,wage,dep_id,tele)values(42,'发动','男','经理',8000.6,41,110); sqlite> select sex,avg(wage) as 平均工资 from employee group by sex;#检索出employee表中不同性别的平均工资 女|9997.7 男|7774.6 sqlite> sqlite> select * from employee order by dep_id,emp_id desc;#先按部门号升序再按员工编号降序检索employee表中全部信息 1399|九九|女|部门经理|17345.0|11|110 1342|九九|女|部门经理|7548.6|11|110 62|花日|男|部门经理|7548.6|11|110 52|二该|女|部门经理|7548.6|11|110 32|花花|男|部门经理|7548.6|11|110 22|二分|女|部门经理|7548.6|11|110 42|发动|男|经理|8000.6|41|110 12|夸克|男|经理|8000.6|41|110 sqlite>