PHP5環(huán)境下采用Sqlite數(shù)據(jù)庫(kù)開(kāi)發(fā)小小總結(jié)
最近花了10多天重新寫(xiě)了泡菜博客,采用了PHP5+SQLITE技術(shù)。原因是MYSQL管理非常麻煩,而且還得花錢(qián)另外買(mǎi)數(shù)據(jù)庫(kù)。
sqlite 是一款輕量級(jí)的、基于文件的嵌入式數(shù)據(jù)庫(kù),2000年就已經(jīng)誕生,經(jīng)過(guò)7年多的發(fā)展,直到今天已經(jīng)成為最流行的嵌入式數(shù)據(jù)庫(kù),包括Google在內(nèi)的公司在其桌面軟件中亦使用 sqlite 存儲(chǔ)用戶(hù)數(shù)據(jù)。由此可以看出,已經(jīng)沒(méi)有任何理由去懷疑sqlite的穩(wěn)定性了。(此段載自藍(lán)雨設(shè)計(jì))
那么如何在PHP5中使用呢?PHP5中有2種連接sqlite的方法。一種是默認(rèn)提供的,另一種是PDO類(lèi)。默認(rèn)的只支持sqlite2,但是PDO可以間接支持sqlite3。下面是我寫(xiě)的簡(jiǎn)單的PDO類(lèi)可以兼容2個(gè)版本。
以下為引用的內(nèi)容:class SQLite{ function __construct($file){ try{ $this->Connection=new PDO('sqlite2:'.$file); }catch(PDOException $e){ try{ $this->Connection=new PDO('sqlite:'.$file); }catch(PDOException $e){ exit('error!'); } } } function __destruct(){ $this->Connection=null; } function Query($SQL){ return $this->Connection->Query($SQL); } function Execute($SQL){ return $this->Query($SQL)->fetch(); } function RecordArray($SQL){ return $this->Query($SQL)->fetchAll(); } function RecordCount($SQL){ return count($this->RecordArray($SQL)); } function RecordLastID(){ return $this->Connection->lastInsertId(); } }
然后實(shí)例化,在實(shí)例化中如果數(shù)據(jù)庫(kù)存在就自動(dòng)打開(kāi),不存在就會(huì)自動(dòng)創(chuàng)建數(shù)據(jù)庫(kù)。
以下為引用的內(nèi)容:$DB=new SQLite('blog.db')//這個(gè)數(shù)據(jù)庫(kù)文件名字任意
創(chuàng)建數(shù)據(jù)庫(kù)表
以下為引用的內(nèi)容:$DB->Query('create table test(id integer primary key,title varchar(50)');
接下來(lái)添加數(shù)據(jù)
以下為引用的內(nèi)容:$DB->Query('insert into test(title) values('泡菜')');$DB->Query('insert into test(title) values('藍(lán)雨')');$DB->Query('insert into test(title) values('Ajan')');$DB->Query('insert into test(title) values('傲雪藍(lán)天')')
之后就是如何讀取數(shù)據(jù)了。也就是循環(huán)。
以下為引用的內(nèi)容:$SQL='select title from test order by id desc';foreach($DB->Query($SQL) as $RS){ echo $RS['title'];}
對(duì)于企業(yè)來(lái)說(shuō)SQLITE可能會(huì)小點(diǎn),但是對(duì)于個(gè)人來(lái)說(shuō)它確實(shí)是個(gè)好東西,可移植性非常好。
本人水平有限,如果以上內(nèi)容有錯(cuò)誤請(qǐng)指正。謝謝!
