資源描述:
《python的sqlite3連接模塊用法》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在應(yīng)用文檔-天天文庫(kù)。
1、python在2.5版以后,就自帶了sqlite3模塊,直接import即可。?模塊可用后,就可以實(shí)現(xiàn)連接sqlite數(shù)據(jù)庫(kù)的功能。sqlite3數(shù)據(jù)庫(kù)與mysql不同,它每一個(gè)庫(kù)叫做一個(gè)文件,連接的時(shí)候,庫(kù)名即文件名,庫(kù)內(nèi)的表則操作方法與mysql相同,或許支持的sql語句會(huì)有一些差異。?我根據(jù)連接mysql的操作方法的包裝,改寫成了這個(gè)sqlite數(shù)據(jù)庫(kù)連接模塊。附件有這個(gè)源碼。??Python代碼??1.#coding=gbk??2.import?os,sys,string??3.import?sql
2、ite3??4.import?traceback??5.??6.class?SQLObj(object):??7.????def?__init__(self,?db?=?'youmoney'):??8.????????self.db_name?=?db??9.????????self.connected?=?0??10.????????self.cur??=?None?#?指針對(duì)象??11.????????self.conn?=?None?#?連接對(duì)象??12.????????self._connect()
3、??13.??14.????def?_connect(self):??15.????????try:??16.????????????#print?"connect?to?",?self.db_name??17.????????????self.conn?=?sqlite3.connect(self.db_name)??18.????????????self.cur?=?self.conn.cursor()??19.????????????self.connected?=?1??1.????????exce
4、pt:??2.????????????traceback.print_exc()??3.????????????self.connected?=?0??4.?5.????@property??6.????def?is_connected(self):??7.????????return?self.connected?!=?0??8.??9.????def?_check_alive(self):??10.????????if?not?self.is_connected:??11.????????????sel
5、f._connect()??12.????????if?not?self.is_connected:??13.????????????raise?"Can't?connect?to?sqlite3"??14.??15.????#直接提取方法??16.????def?query(self,?sql,?warning=1):??17.????????self._check_alive()??18.????????try:??19.????????????cur?=?self.conn.cursor()??20.
6、????????????cur.execute(sql)??21.????????????res?=?cur.fetchall()??22.????????????cur.close()??23.????????except:??24.????????????if?warning:??25.????????????????traceback.print_exc()??26.????????????return?None??27.????????return?res??28.??29.??30.????#特殊
7、的提取方法,形成字典返回??31.????def?dquery(self,?sql,?warning=1):??32.????????self._check_alive()??33.????????try:??34.????????????cur?=?self.conn.cursor()??35.????????????cur.execute(sql)??36.??????????????37.????????????des?=?cur.description?#獲取字段描述??38.???????????
8、?res?=?cur.fetchall()??#獲取字段內(nèi)容??39.????????????ret?=?[]??40.????????????if?des:??1.????????????????names?=?[x[0]?for?x?in?des]?#從des中提取每個(gè)元素(列表)的第一個(gè)元素(字符串)??2.????????????????for?line?in?res:??3.??????????????