经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MS SQL Server » 查看文章
SQLite3 of python
来源:cnblogs  作者:步平凡  时间:2019/5/27 8:46:46  对本文有异议

SQLite3 of python

一、SQLite3 数据库

  SQLite3 可使用 sqlite3 模块与 Python 进行集成,一般 python 2.5 以上版本默认自带了sqlite3模块,因此不需要用户另外下载。

在 学习基本语法之前先来了解一下数据库是使用流程吧 ↓↓↓

所以,首先要创建一个数据库的连接对象,即connection对象,语法如下:

sqlite3.connect(database [,timeout,其他可选参数])

function: 此API打开与SQLite数据库文件的连接。如果成功打开数据库,则返回一个连接对象。

database: 数据库文件的路径,或 “:memory:” ,后者表示在RAM中创建临时数据库。

timeout: 指定连接在引发异常之前等待锁定消失的时间,默认为5.0(秒)

 

有了connection对象,就能创建游标对象了,即cursor对象,如下:

connection.cursor([cursorClass])

function: 创建一个游标,返回游标对象游标将在Python的整个数据库编程中使用。

 

接下来,看看connection对象 和 cursor对象的 “技能” 吧  ↓↓↓

connection对象的方法
方法 说明
connect.cursor() 上述,返回游标对象
connect.execute(sql [,parameters]) 创建中间游标对象执行一个sql命令
connect.executemany(sql [,parameters]) 创建中间游标对象执行一个sql命令
connect.executescript(sql_script) 创建中间游标对象, 以脚本的形式执行sql命令
connect.total_changes() 返回自打开数据库以来,已增删改的行的总数
connect.commit() 提交当前事务,不使用时为放弃所做的修改,即不保存
connect.rollback() 回滚自上次调用commit()以来所做的修改,即撤销
connect.close() 断开数据库连接

 

cursor对象的方法
方法 说明
cursor.execute(sql [,parameters]) 执行一个sql命令
cursor.executemany(sql,seq_of_parameters) 对 seq_of_parameters 中的所有参数或映射执行一个sql命令
cursor.executescript(sql_script) 以脚本的形式一次执行多个sql命令
cursor.fetchone() 获取查询结果集中的下一行,返回一个单一的序列,当没有更多可用的数据时,则返回 None。
cursor.fetchmany([size=cursor.arraysize]) 获取查询结果集中的下一行组,返回一个列表。当没有更多的可用的行时,则返回一个空的列表。size指定特定行数。
cursor.fetchall() 获取查询结果集中所有(剩余)的行,返回一个列表。当没有可用的行时,则返回一个空的列表。

下面用一个简单实例作为介绍 >>>

  1. 1 def SQLite_Test():
  2. 2 # =========== 连接数据库 ============
  3. 3 # 1. 连接本地数据库
  4. 4 connectA = sqlite3.connect("example.db")
  5. 5 # 2. 连接内存数据库,在内存中创建临时数据库
  6. 6 connectB = sqlite3.connect(":memory:")
  7. 7
  8. 8 # =========== 创建游标对象 ============
  9. 9 cursorA = connectA.cursor()
  10. 10 cursorB = connectB.cursor()
  11. 11
  12. 12 # =========== 创建表 ============
  13. 13 cursorA.execute("CREATE TABLE class(id real, name text, age real, sex text)")
  14. 14 cursorB.execute("CREATE TABLE family(relation text, job text, age real)")
  15. 15
  16. 16 # =========== 插入数据 ============
  17. 17 cursorA.execute("INSERT INTO class VALUES(1,'Jock',8,'M')")
  18. 18 cursorA.execute("INSERT INTO class VALUES(2,'Mike',10,'M')")
  19. 19 # 使用 ? 占位符
  20. 20 cursorA.execute("INSERT INTO class VALUES(?,?,?,?)", (3,'Sarah',9,'F'))
  21. 21
  22. 22 families = [
  23. 23 ['Dad', 'CEO', 35],
  24. 24 ['Mom', 'singer', 33],
  25. 25 ['Brother', 'student', 8]
  26. 26 ]
  27. 27 cursorB.executemany("INSERT INTO family VALUES(?,?,?)",families)
  28. 28
  29. 29 # =========== 查找数据 ============
  30. 30 # 使用 命名变量 占位符
  31. 31 cursorA.execute("SELECT * FROM class WHERE sex=:SEX", {"SEX":'M'})
  32. 32 print("TABLE class: >>>select Male\n", cursorA.fetchone())
  33. 33 cursorA.close()
  34. 34
  35. 35 cursorB.execute("SELECT * FROM family ORDER BY relation")
  36. 36 print("TABLE family:\n", cursorB.fetchall())
  37. 37 cursorB.close()
  38. 38
  39. 39 # =========== 断开连接 ============
  40. 40 connectA.close()
  41. 41 connectB.close()
  42. 42
  43. 43 SQLite_Test()

  运行结果:

TABLE class: >>>select Male
(1.0, 'Jock', 8.0, 'M')
TABLE family:
[('Brother', 'student', 8.0), ('Dad', 'CEO', 35.0), ('Mom', 'singer', 33.0)]

 

 二、小练手

使用目前学的sqlite3数据库知识,对一些数据进行增删查改的操作。此处选择来自下面网站的数据

url = http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html 

先将数据从网站上爬取下来,存储为csv文件,然后再保存到数据库中,接着进行数据的操作。对于如何存储为csv文件,请查看 >>> 《此处的最后一个小主题

对于本次小练习的介绍:

目的:对已爬取的数据进行数据库管理和简单操作

步骤: 创建数据库文件 >>> 创建表 >>> 保存数据到数据库 >>> 对数据进行简单操作

方法:我采用的方法是:

① 编写一个函数( get_data(fileName) ):读取csv文件中的数据,主要完成对数据的格式转换,以便适合保存到数据库中

② 编写一个函数类( class SQL_method ):对数据库进行简单操作,主要完成数据库的创建和数据的保存

③ 尝试其他操作:

a. 在数据库中查找某一项记录

b. 对数据按照某种排序输出

c. 对数据进行增加权值操作,实现重新排序

d. 删除数据库中的某些记录

e. 删除数据库中的表

好了,有了前进的方向,那我们杨帆 ----- 起航 >>>

  1. 1 # -*- coding: utf-8 -*-
  2. 2 '''
  3. 3 使用 url = "http://www.zuihaodaxue.cn/zuihaodaxuepaiming2016.html" 的数据进行SQLite3数据库的练习使用
  4. 4 @author: bpf
  5. 5 '''
  6. 6
  7. 7 import sqlite3
  8. 8
  9. 9 class SQL_method:
  10. 10 '''
  11. 11 function: 可以实现对数据库的基本操作
  12. 12 '''
  13. 13 def __init__(self, dbName, tableName, data, columns, Read_All=True):
  14. 14 '''
  15. 15 function: 初始化参数
  16. 16 dbName: 数据库文件名
  17. 17 tableName: 表的名称
  18. 18 data: 从csv文件中读取且经过处理的数据
  19. 19 columns: 表的第一行
  20. 20 '''
  21. 21 self.dbName = dbName
  22. 22 self.tableName = tableName
  23. 23 self.data = data
  24. 24 self.columns = columns
  25. 25 self.Read_All = Read_All
  26. 26
  27. 27 def creatTable(self):
  28. 28 '''
  29. 29 function: 创建数据库文件及相关的表
  30. 30 '''
  31. 31 # 连接数据库
  32. 32 connect = sqlite3.connect(self.dbName)
  33. 33 # 创建表
  34. 34 connect.execute("CREATE TABLE {}{}".format(self.tableName, self.columns))
  35. 35 # 提交事务
  36. 36 connect.commit()
  37. 37 # 断开连接
  38. 38 connect.close()
  39. 39
  40. 40 def destroyTable(self):
  41. 41 '''
  42. 42 function: 删除数据库文件中的表
  43. 43 '''
  44. 44 # 连接数据库
  45. 45 connect = sqlite3.connect(self.dbName)
  46. 46 # 删除表
  47. 47 connect.execute("DROP TABLE {}".format(self.tableName))
  48. 48 # 提交事务
  49. 49 connect.commit()
  50. 50 # 断开连接
  51. 51 connect.close()
  52. 52
  53. 53 def insertDataS(self):
  54. 54 '''
  55. 55 function: 向数据库文件中的表插入多条数据
  56. 56 '''
  57. 57 # 连接数据库
  58. 58 connect = sqlite3.connect(self.dbName)
  59. 59 # 插入多条数据
  60. 60 connect.executemany("INSERT INTO {} VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)".format(self.tableName), self.data)
  61. 61 #for i in range(len(self.data)):
  62. 62 # connect.execute("INSERT INTO university VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)", data[i])
  63. 63 # 提交事务
  64. 64 connect.commit()
  65. 65 # 断开连接
  66. 66 connect.close()
  67. 67
  68. 68 def getAllData(self):
  69. 69 '''
  70. 70 function: 得到数据库文件中的所有数据
  71. 71 '''
  72. 72 # 连接数据库
  73. 73 connect = sqlite3.connect(self.dbName)
  74. 74 # 创建游标对象
  75. 75 cursor = connect.cursor()
  76. 76 # 读取数据
  77. 77 cursor.execute("SELECT * FROM {}".format(self.tableName))
  78. 78 dataList = cursor.fetchall()
  79. 79 # 断开连接
  80. 80 connect.close()
  81. 81 return dataList
  82. 82
  83. 83 def run(self):
  84. 84 try:
  85. 85 # 创建数据库文件
  86. 86 self.creatTable()
  87. 87 print("SQL creats successfully!")
  88. 88 # 保存数据到数据库
  89. 89 self.insertDataS()
  90. 90 print("Insert data successfully!")
  91. 91 except:
  92. 92 print("SQL has created!")
  93. 93 # 读取所有数据
  94. 94 if self.Read_All:
  95. 95 for i in self.getAllData():
  96. 96 print(i)
  97. 97
  98. 98 def get_data(fileName):
  99. 99 '''
  100. 100 function: 读取获得大学排名的数据 并 将结果返回
  101. 101 '''
  102. 102 data = []
  103. 103 # 打开文件
  104. 104 f = open(fileName, 'r', encoding='utf-8')
  105. 105 # 按行读取文件
  106. 106 for line in f.readlines():
  107. 107 # 替换掉其中的换行符
  108. 108 line = line.replace('\n', '')
  109. 109 # 将列表转化为元组
  110. 110 li = tuple(line.split(','))
  111. 111 data.append(li)
  112. 112 columns = ("Rank text", "University text", "Province text", "Grade text", "SourseQuality text", "TrainingResult text", "ResearchScale text",
  113. 113 "ReserchQuality text", "TopResult text", "TopTalent text", "TechnologyService text", "Cooperation text", "TransformationResults text")
  114. 114 # 分别对应: ["排名", "学校名称", "省市", "总分", "生涯质量", "培养结果", "科研规模", "科研质量", "顶尖成果", "顶尖人才", "科技服务", "产学研合作", "成果转化"]
  115. 115 return columns, data[1:]
  116. 116
  117. 117 if __name__ == "__main__":
  118. 118 # 设置和得到基本数据
  119. 119 fileName = "D:\\University_Rank.csv"
  120. 120 columns, data = get_data(fileName)
  121. 121 dbName = "university.db"
  122. 122 tableName = "university"
  123. 123 # 创建SQL_method的一个对象
  124. 124 SQL = SQL_method(dbName, tableName, data, columns, False)
  125. 125 # 创建数据库文件和保存数据
  126. 126 SQL.run()

 

 未完待续 。。。

 

 

 

 

原文链接:http://www.cnblogs.com/bpf-1024/p/10928456.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号