本人初次接触数据库, 在自己练习的时候遇到了一点问题查阅了资料以后还是没有找到答案, 几个问题如下:
问题1: sqlite3 的连接该如何放置?
之前我都是写一个函数, 比如叫db_connect
, 会返回sqlite3
的连接, 网上查阅了资料说直接把conn
作为全局变量就行, 然后如果有多个模块引用conn
就需要考虑ORM
了, 链接为该问题下面的评论, 我复制了如下:
yes, for simple code, just open the connection at the top of the script and use it without creating a function. if you have several modules and you find that you want the same connection to be used in all of them (DRY principal), that's the time to start seriously thinking about an ORM
我的问题在于我不需要使用ORM
, 那么该如何写? 比如我有两个model
, Student
和Teacher
, 都有对数据库的增删改查, 那么我想到这两种写法:
第一种直接import
连接
# student.py
conn = sqlite3.connect(db_filename)
class Student:
pass
# teacher.py
from student import conn
class Teacher:
pass
第二种再创建一条连接
conn = sqlite3.connect(db_filename)
class Student:
pass
# teacher.py
conn = sqlite3.connect(db_filename)
class Teacher:
pass
两种方法哪种更好? 以及对于第二种, 如果有多个连接指向一个数据库, 会造成任何问题么?
问题2: curosr关闭的问题?
对于每一个query
执行完毕以后是否需要手动关闭cursor
的连接? 这个问题其实有人提过, 问题在这, stackoverflow 上面也说不关闭也会被垃圾回收, 也没有更多详细的解释, 所以还是请教一下到底也没有必要关闭cursor
?
问题有点混乱, 还请各位前辈见谅, 若有不明白的地方也请及时指出, 若能解答, 不胜感激!