Dotcpp  >  编程教程  >  Python数据库管理  >  SQlite数据库(2)

SQlite数据库(2)

点击打开在线编译器,边学边练

1. 查看数据

        查看表中的数据使select语句,它的语法格式为:

cursor = con.execute("select 字段1,字段2...(id,name...). from 表名(user) where 查询条件")

        我们在查询数据的时候可以通过多种方式:

        1) 使用fetchone()方法来查询结果中的下一条信息。

        2) 使用fetchmany(size)方法来获取size数量的记录。

        3) 使用fetchall()方法来查看所有记录。

        代码如下:

import sqlite3
con = sqlite3.connect('test.db')
cursor =  con.cursor()
cursor.execute('select * from user')
print('第一种方式:')
print(cursor.fetchone())
print(cursor.fetchone())
print(cursor.fetchone())
print('第二种方式:')
print(cursor.fetchmany(2))
print('第三种方式:')
print(cursor.fetchall())
cursor.close()
con.commit()
con.close()

        注意使用每一种方式的时候把其它两种方式删除掉,输出结果为:

 第一种方式:
 (1001, '李华', 21)
 (1002, '小明', 20)
 (1003, '小张', 21)
 第二种方式:
 [(1001, '李华', 21), (1002, '小明', 20)]
 第三种方式:[(1001, '李华', 21), (1002, '小明', 20), (1003, '小张', 21)]

        第一种方式是依次查询,第二种方式指定了查询数量为2,第三种方式为全部查询。

        下面我们再介绍一种方式:

import sqlite3
con = sqlite3.connect('test.db')
cursor =  con.cursor()
cursor.execute('select * from user')
for row in cursor:
   print ("id = ", row[0],"name = ", row[1],"age = ", row[2])
cursor.close()
con.commit()
con.close()

        输出结果为:

id =  1001 name =  李华 age =  21
id =  1002 name =  小明 age =  20
id =  1003 name =  小张 age =  21

        这种方式我们可以通过索引获得每个元素对应的值。

2. 修改数据

        修改数据使用update方法,语法格式为:

con.execute("update 表名(user) set 字段名(age) = 字段值(21) where 查询条件(id=1002)")

        我们通过下面代码来看一下:

import sqlite3
con = sqlite3.connect('test.db')
cursor =  con.cursor()
cursor.execute('select * from user')
for row in cursor:
   print ("id = ", row[0],"name = ", row[1],"age = ", row[2])
cursor.close()
con.commit()
con.close()

        输出结果为:

id =  1001 name =  李华 age =  21
id =  1002 name =  小明 age =  20
id =  1003 name =  小张 age =  21

        我们可以通过输出结果看出数据已经被修改。

3. 删除数据

        删除数据的方式为:

con.execute("delete from 表名(user) where 条件(id = 1002)")

        我们通过代码看一下:

import sqlite3
con = sqlite3.connect('test.db')
cursor =  con.cursor()
con.execute("delete from user where id = 1002;")
cursor.execute('select * from user')
for row in cursor:
   print ("id = ", row[0],"name = ", row[1],"age = ", row[2])
cursor.close()
con.commit()
con.close()

        输出结果为:

id =  1001 name =  李华 age =  21
id =  1003 name =  小张 age =  21

        可以看出id为1002的数据已经被删除。

4. 总结

        通过这两节的学习,我们来回顾一下操作流程:

        1) 首先要连接到数据库文件。

        2) 然后创建一个游标来进行相关操作。

        3) 如果是增加数据一定要注意主键的唯一性,不能插入相同的主键信息。

        4) 如果是删除数据时,在选择条件的时候,会删除满足条件的所有项。

        5) 查看数据的时候有多种方式可选择。

        6) 关闭游标。

        7) 提交事务。

        8) 关闭连接。

        大家在使用的过程中通过这个顺序能够保证我们程序的正确性。



本文固定URL:https://www.dotcpp.com/course/309

Python教程
第一章 Python入门
第二章 Python基础语法
第三章 Python入门语法
第四章 Python核心语法
第五章 Python函数
第六章 Python面向对象编程
第七章 Python模块
第八章 Python异常处理和程序调试
第九章 Python文件及目录操作
第十章 PythonGUI编程
第十一章 Python进程和线程
第十二章 Python数据库管理
第十三章 Python算法
第十四章 Python爬虫
第十五章 Python实战项目
第十六章 后记
Dotcpp在线编译      (登录可减少运行等待时间)