PDO的三种数据库连接方式

来源:互联网 发布:篮球战术软件 编辑:程序博客网 时间:2024/04/19 00:53

在使用PDO连接数据库之前,先要对PDO安装和配置

base.php如下:

<strong><span style="font-size:18px;"><?php  header('Content-Type:text/html;charset=utf-8');//数组调试函数function show_bug($msg){echo '<pre>';print_r($msg);echo '</pre>';}?></span></strong>

1.pdo通过参数形式链接数据库

<strong><span style="font-size:18px;">include_once "base.php";try{    //$dsn是数据源    $dsn='mysql:host=localhost;dbname=imooc';    $username='root';    $passwd='';    $pdo=new PDO($dsn,$username,$passwd);    //如果连接成功的话,得到的是pdo的对象    show_bug($pdo);}catch(PDOException $e){    echo $e->getMessage();}</span></strong>
2.pdo通过uri形式连接数据库
新建一个dsn.txt文件,里面内容是:

<strong><span style="font-size:18px;"><?php  include_once "base.php";//pdo通过uri形式连接数据库try{$dsn='uri:file://D:\wamp\www\muke\pdo\dsn.txt';$username='root';$passwd='';$pdo=new PDO($dsn,$username,$passwd);show_bug($pdo);}catch(PDOException $e){echo $e->getMessage();}?></span></strong>
3.pdo通过配置文件形式连接数据库

<strong><span style="font-size:18px;"><?php  include_once "base.php";//pdo通过配置文件形式连接数据库//在php.ini中配置try{$dsn='imooc';$username='root';$passwd='';$pdo=new PDO($dsn,$username,$passwd);show_bug($pdo);}catch(PDOException $e){echo $e->getMessage(); }?></span></strong>

以上三种,建议使用第一种,通过参数形式链接数据库的

1 0
原创粉丝点击