进入 PHPChina 首页
当前位置:PHPChina 开源社区门户 - 数据库相关 - 正文
[字号:  ]

PHP中使用PDO访问SQLite教程

发布时间:2008-11-11 15:29   作者: 网络转载   信息来源: www.phpq.net  [我来说两句(207条)]

本文详细介绍在PHP5中使用PDO访问SQLite3的方法,并以两个PHP实例代码,作为PHP操作SQLite教程

PHP中使用PDO访问SQLite教程代码1:

<html>
<?php
$dsn = 'sqlite:sql.db';
try
{
$dbh = new PDO($dsn, $user, $password);  //建立连接
echo 'PDO Connection Ok<BR>';
//建表
$dbh->exec("CREATE TABLE PKU(id integer,name varchar(255))");
//echo 'Create Table ok<BR>
';
print("Create Table ok<BR>
");
$dbh->exec("INSERT INTO PKU values(1,'jarjin')");
echo 'Insert Data ok<BR>';
$dbh->beginTransaction();
$sth = $dbh->prepare('SELECT * FROM PKU');
$sth->execute();
//获取结果
$result = $sth->fetchAll();
print_r($result);
$dsn=null;
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
$dsn = null;
}
?>
</html>

PHP中使用PDO访问SQLite教程代码2:

<html>
<?php
//$pdo = new PDO('sqlite::memory:');  //内存中的数据库
$pdo = new PDO('sqlite:mydb.db');
$pdo->exec('CREATE TABLE test(ID INT NOT NULL PRIMARY KEY, Field VARCHAR(12) NULL);');
$stmt = $pdo->prepare('INSERT INTO test(ID, Field) VALUES(?, ?)');
$one = 1;
$two = 2;
$null = NULL;
// Try with PDO_PARAM_NULL
$stmt->bindParam(1, $one, PDO::PARAM_INT);  //绑定参数
$stmt->bindParam(2, $null, PDO::PARAM_STR);
assert($stmt->execute());
// Try with PDO_PARAM_STR
$stmt->bindParam(1, $two, PDO::PARAM_INT);
$stmt->bindParam(2, $null, PDO::PARAM_STR);
assert($stmt->execute());
// Check we have rows..
$stmt = $pdo->prepare('SELECT * FROM test');
assert($stmt->execute());
var_dump($stmt->fetchAll());
// Check we have rows with field is null
echo '<hr />';
$stmt = $pdo->prepare('SELECT * FROM test WHERE Field IS NULL');
assert($stmt->execute());
var_dump($stmt->fetchAll());  //显示查询结果
?>
</html>

注:本文是在PHP5中使用PDO来实现对SQLite的操作,请大家注意自己实际操作中PHP的版本。

TAG: pdo PDO PHP sqlite 访问 教程 SQLite

字号:   | 推荐给好友

[我来说两句(207条)]
现在有0人对本文发表评论 查看全部评论>>评论区

 

评分:0

验证码: seccode