欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Windows平臺(tái)Python連接sqlite3數(shù)據(jù)庫的方法分析

 更新時(shí)間:2017年07月12日 09:25:21   作者:不想長大啊  
這篇文章主要介紹了Windows平臺(tái)Python連接sqlite3數(shù)據(jù)庫的方法,結(jié)合實(shí)例形式分析了Windows平臺(tái)安裝SQLite數(shù)據(jù)庫及創(chuàng)建、連接數(shù)據(jù)庫的實(shí)現(xiàn)方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下

本文實(shí)例講述了Windows平臺(tái)Python連接sqlite3數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:

之前沒有接觸過sqlite數(shù)據(jù)庫,只是聽到同事聊起這個(gè)。

有一次,手機(jī)端同事讓我?guī)椭鴮憘€(gè)sql,后面說運(yùn)行不了報(bào)錯(cuò)了,我問是什么數(shù)據(jù)庫,同事說是sqlite,這才知道了還有sqlite這個(gè)數(shù)據(jù)庫。。。

接下來說說Python連接sqlite數(shù)據(jù)庫,非常簡單,因?yàn)閜ython中的sqlite模塊也遵循了DB-API 2.0的規(guī)范,所以操作起來和sql server、MySQL、oracle數(shù)據(jù)庫都是一樣的。

一、在 Windows 上安裝 SQLite:

(1)請(qǐng)?jiān)L問 SQLite 下載頁面,從 Windows 區(qū)下載預(yù)編譯的二進(jìn)制文件:http://www.sqlite.org/download.html

(2)因?yàn)槲业膚in 7是64位的,所以下載 sqlite-shell-win64-*.zip 和 sqlite-dll-win64-*.zip 壓縮文件,如果你的系統(tǒng)是32位的就下載32位的版本。

(3)創(chuàng)建文件夾 C:\sqlite,并在此文件夾下解壓上面兩個(gè)壓縮文件,將得到 sqlite3.def、sqlite3.dll 和 sqlite3.exe 文件。

(4)添加 C:\sqlite 到 PATH 環(huán)境變量,最后在命令提示符下,使用 sqlite3 命令,將顯示如下結(jié)果:

C:\Users\Administrator>sqlite3
SQLite version 3.15.2 2016-11-28 19:13:37
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.
sqlite>

二、創(chuàng)建一個(gè)數(shù)據(jù)庫test.db

直接用命令行sqlite3創(chuàng)建數(shù)據(jù)庫,然后用命令.database 查詢系統(tǒng)中的數(shù)據(jù)庫。

C:\Users\Administrator>sqlite3 test.db
SQLite version 3.15.2 2016-11-28 19:13:37
Enter ".help" for usage hints.
sqlite> .database
seq name       file
--- --------------- ----------------------------------------------------------
0  main       C:\Users\Administrator\test.db

注意:不要退出,因?yàn)榻酉聛韕ython要連接數(shù)據(jù)庫(最后關(guān)閉數(shù)據(jù)庫時(shí),可以用.quit 命令退出sqlite3)。

三、python連接sqlite3

python中內(nèi)置了sqlite模塊,所以不需要安裝,導(dǎo)入后就可以直接用。

需要特別注意的是,要把編寫好的程序文件放到 test.db數(shù)據(jù)庫相同的目錄,這里是:C:\Users\Administrator,否則會(huì)發(fā)現(xiàn)程序中會(huì)創(chuàng)建一個(gè)新的test.db,并且是在當(dāng)前程序運(yùn)行的目錄下,就查看不到數(shù)據(jù)庫的變化了。

# -*- coding:gbk -*-
import sqlite3
conn = sqlite3.connect('test.db')
cur = conn.cursor()
cur.execute('create table t(id int,v varchar(20));');
cur.execute("insert into t values(%d,'%s')" % (1,'xxx'))
cur.execute("insert into t values(%d,'%s')" % (2,'yyy'))
cur.execute("update t set v = '%s' where id = %d" % ('zzz',2))
cur.execute("select * from t;")
results = cur.fetchall()
for row in results:
  print row
conn.commit()
cur.close()
conn.close()

每條數(shù)據(jù)都是一個(gè)元祖,所有記錄組成了一個(gè)列表。

輸出結(jié)果:

================ RESTART: C:\Users\Administrator\Desktop\r.py ================
(1, u'xxx')
(2, u'zzz')

代碼非常簡單,其實(shí)python連接sqlite3就是這么的簡單

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論