《PHP使用PDO连接SQLITE3》要点:
本文介绍了PHP使用PDO连接SQLITE3,希望对您有用。如果有疑问,可以联系我们。
PHP可以通过直接的方法对sqlite数据库进行操作。不过提但是使用PDO进行连接。这里是一个封装示例,希望能帮到您。
注意:
sqlite在连接失败后会自动创建一个空数据库文件,所以在connect_sqlite方法中直接判断若此文件不存在则不进行库连接操作。
PHP用PDO调用SQLITE示例:
$sqlitedb = new db_sqlite; $conn = $sqlitedb->connect_sqlite('./db/sqlite3.db',''); $sqlitedb->exec_sqlite($conn,"insert into tt2 values(2,'http://www.vephp.com')"); $sqlitedb->commit_sqlite($conn); $rs = $sqlitedb->query_sqlite($conn,'select * from tt2'); foreach($rs as $k=>$v) { $v1 = $v['name']; #$v1 = mb_convert_encoding($v1,"gb2312","utf-8"); #$v1 = mb_convert_encoding($v1,"utf-8","gb2312"); echo $v1,'<br />'; } $sqlitedb->close_sqlite($conn);
PDO连接SQLITE3的通用类:
/** * 此类只兼容sqlite3 * @author hanxiaoyue */ class db_sqlite { //打开sqlite数据库 function connect_sqlite($dbname,$module) { $conn = null; if(file_exists($dbname)) { $dbPath = 'sqlite:'.$dbname; try { $conn = new PDO($dbPath); $conn->beginTransaction(); } catch(PDOException $e) { echo 'Exception is:'.$e->getMessage(); } return $conn; } else { exit('连接时出现错误!'); } } //打开datafarm链接 function connect_datafarm_sqlite($dbname) { $conn = null; if(file_exists($dbname)) { $dbPath = 'sqlite:'.$dbname; try { $conn = new PDO($dbPath); $conn->beginTransaction(); } catch(PDOException $e) { echo 'Exception is:'.$e->getMessage(); } return $conn; } else { exit('启动事务时出现错误!'); } } //查询操作 function query_sqlite($conn,$sql) { $result = array(); try { $sth = $conn->prepare($sql); $sth->execute(); //获取结果 $result = $sth->fetchAll(); } catch(PDOException $e) { echo 'Exception is:'.$e->getMessage(); } return $result; } //查询总记录数 function query_count($conn,$sql) { $result = 0; try { $sth = $conn->prepare($sql); $sth->execute(); //获取结果 $vec = $sth->fetchAll(); $result = $vec[0]['c']; } catch(PDOException $e) { echo 'Exception is:'.$e->getMessage(); } return $result; } //add,update,delete执行操作 function exec_sqlite($conn,$sql) { $count = 0; try { $count = $conn->exec($sql); } catch(PDOException $e) { $conn->rollBack(); echo 'Exception is:'.$e->getMessage(); } return $count; } /** * 提交事务。针对执行exec_sqlite后 */ function commit_sqlite($conn) { $conn->commit(); } //关闭连接 function close_sqlite($conn) { $conn=null; } }
转载请注明本页网址:
http://www.vephp.com/jiaocheng/87.html