站长论坛

标题: PHP中使用PDO访问SQLite教程 [打印本页]

作者: tznktg    时间: 2008-11-12 16:14
标题: PHP中使用PDO访问SQLite教程
本文详细介绍在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的版本。

[ 本帖最后由 tznktg 于 2008-11-12 16:16 编辑 ]




欢迎光临 站长论坛 (https://tzlink.com/bbs/) Powered by Discuz! X3.2