程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> 簡潔的PHP操作SQLite類

簡潔的PHP操作SQLite類

編輯:PHP綜合
SQLite是一款輕型的數據庫,是遵守ACID的關聯式數據庫管理系統,它的設計目標是嵌入式的,而且目前已經在很多嵌入式產品中使用了它,它占用資源非常的低,在嵌入式設備中,可能只需要幾百K的內存就夠了。它能夠支持Windows/Linux/Unix等等主流的操作系統,同時能夠跟很多程序語言相結合,比如Tcl、PHP、Java等,還有ODBC接口,同樣比起Mysql、PostgreSQL這兩款開源世界著名的數據庫管理系統來講,它的處理速度比他們都快。

這裡為大家提供一個簡潔的PHP操作SQLite類:

<?php
/***
//應用舉例
require_once('cls_sqlite.php');
//創建實例
$DB=new SQLite('blog.db'); //這個數據庫文件名字任意
//創建數據庫表。
$DB->query("create table test(id integer primary key,title varchar(50))");
//接下來添加數據
$DB->query("insert into test(title) values('泡菜')");
$DB->query("insert into test(title) values('藍雨')");
$DB->query("insert into test(title) values('Ajan')");
$DB->query("insert into test(title) values('傲雪藍天')");
//讀取數據
print_r($DB->getlist('select * from test order by id desc'));
//更新數據
$DB->query('update test set title = "三大" where id = 9');
***/

class SQLite
{
function __construct($file)
{
try
{
$this->connection=new PDO('sqlite:'.$file);
}
catch(PDOException $e)
{
try
{
$this->connection=new PDO('sqlite2:'.$file);
}
catch(PDOException $e)
{
exit('error!');
}
}
}

function __destruct()
{
$this->connection=null;
}

function query($sql) //直接運行SQL,可用於更新、刪除數據
{
return $this->connection->query($sql);
}

function getlist($sql) //取得記錄列表
{
$recordlist=array();
foreach($this->query($sql) as $rstmp)
{
$recordlist[]=$rstmp;
}
return $recordlist;
}

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();
}
}
?>
  

相關 PHP 配置說明:

1. 先測試 PHP 能否連接 sqlite 數據庫:

建立一個php文件

<?php
$conn = sqlite_open('test.db');
?>
  

測試這個文件能否正常運行。

如果沒有能正常加載sqlite模塊,就可能出現這樣的錯誤:

Fatal error: Call to undefined function sqlite_open() in C:\Apache\Apache2\htdocs\test.php on line 2

解決辦法如下:

2. 打開 php.ini 文件,將以下三行前面的分號刪除:

;extension=php_sqlite.dll
;extension=php_pdo.dll
;extension=php_pdo_sqlite.dll

重新啟動web服務器
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved