1. 使用SQLite
    2. 阅读: 94640
    3. SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,甚至在iOSAndroidApp中都可以集成。
    4. Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。
    5. 在使用SQLite前,我们先要搞清楚几个概念:
    6. 表是数据库中存放关系数据的集合,一个数据库里面通常都包含多个表,比如学生的表,班级的表,学校的表,等等。表和表之间通过外键关联。
    7. 要操作关系数据库,首先需要连接到数据库,一个数据库连接称为Connection
    8. 连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果。
    9. Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可。
    10. 由于SQLite的驱动内置在Python标准库中,所以我们可以直接来操作SQLite数据库。
    11. 我们在Python交互式命令行实践一下:
    12. # 导入SQLite驱动:
    13. >>> import sqlite3
    14. # 连接到SQLite数据库
    15. # 数据库文件是test.db
    16. # 如果文件不存在,会自动在当前目录创建:
    17. >>> conn = sqlite3.connect('test.db')
    18. # 创建一个Cursor:
    19. >>> cursor = conn.cursor()
    20. # 执行一条SQL语句,创建user表:
    21. >>> cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
    22. <sqlite3.Cursor object at 0x10f8aa260>
    23. # 继续执行一条SQL语句,插入一条记录:
    24. >>> cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')
    25. <sqlite3.Cursor object at 0x10f8aa260>
    26. # 通过rowcount获得插入的行数:
    27. >>> cursor.rowcount
    28. 1
    29. # 关闭Cursor:
    30. >>> cursor.close()
    31. # 提交事务:
    32. >>> conn.commit()
    33. # 关闭Connection:
    34. >>> conn.close()
    35. 我们再试试查询记录:
    36. >>> conn = sqlite3.connect('test.db')
    37. >>> cursor = conn.cursor()
    38. # 执行查询语句:
    39. >>> cursor.execute('select * from user where id=?', ('1',))
    40. <sqlite3.Cursor object at 0x10f8aa340>
    41. # 获得查询结果集:
    42. >>> values = cursor.fetchall()
    43. >>> values
    44. [('1', 'Michael')]
    45. >>> cursor.close()
    46. >>> conn.close()
    47. 使用PythonDB-API时,只要搞清楚ConnectionCursor对象,打开后一定记得关闭,就可以放心地使用。
    48. 使用Cursor对象执行insertupdatedelete语句时,执行结果由rowcount返回影响的行数,就可以拿到执行结果。
    49. 使用Cursor对象执行select语句时,通过featchall()可以拿到结果集。结果集是一个list,每个元素都是一个tuple,对应一行记录。
    50. 如果SQL语句带有参数,那么需要把参数按照位置传递给execute()方法,有几个?占位符就必须对应几个参数,例如:
    51. cursor.execute('select * from user where name=? and pwd=?', ('abc', 'password'))
    52. SQLite支持常见的标准SQL语句以及几种常见的数据类型。具体文档请参阅SQLite官方网站。
    53. 小结
    54. Python中操作数据库时,要先导入数据库对应的驱动,然后,通过Connection对象和Cursor对象操作数据。
    55. 要确保打开的Connection对象和Cursor对象都正确地被关闭,否则,资源就会泄露。
    56. 如何才能确保出错的情况下也关闭掉Connection对象和Cursor对象呢?请回忆try:...except:...finally:...的用法。
    57. 练习
    58. 请编写函数,在Sqlite中根据分数段查找指定的名字:
    59. # -*- coding: utf-8 -*-
    60. import os, sqlite3
    61. db_file = os.path.join(os.path.dirname(__file__), 'test.db')
    62. if os.path.isfile(db_file):
    63. os.remove(db_file)
    64. # 初始数据:
    65. conn = sqlite3.connect(db_file)
    66. cursor = conn.cursor()
    67. cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)')
    68. cursor.execute(r"insert into user values ('A-001', 'Adam', 95)")
    69. cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")
    70. cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")
    71. cursor.close()
    72. conn.commit()
    73. conn.close()
    74. def get_score_in(low, high):
    75. ' 返回指定分数区间的名字,按分数从低到高排序 '
    76. ----
    77. pass
    78. ----
    79. # 测试:
    80. assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)
    81. assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)
    82. assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100)
    83. print('Pass')
    84. 参考源码
    85. do_sqlite.py