连接与连接管理
来源:互联网 发布:无需备案的域名 编辑:程序博客网 时间:2024/05/17 02:43
连接与连接管理
连接是通过创建 PDO 基类的实例而建立的。不管使用哪种驱动程序,都是用 PDO 类名。构造函数接收用于指定数据库源(所谓的 DSN)以及可能还包括用户名和密码(如果有的话)的参数
Example #1 连接到 MySQL
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
?>
如果有任何连接错误,将抛出一个 PDOException 异常对象。如果想处理错误状态,可以捕获异常,或者选择留给通过 set_exception_handler() 设置的应用程序全局异常处理程序。
Example #2 处理连接错误
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
连接数据成功后,返回一个 PDO 类的实例给脚本,此连接在 PDO 对象的生存周期中保持活动。要想关闭连接,需要销毁对象以确保所有剩余到它的引用都被删除,可以赋一个 NULL
值给对象变量。如果不明确地这么做,PHP 在脚本结束时会自动关闭连接。
Example #3 关闭一个连接
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// 在此使用连接
// 现在运行完成,在此关闭连接
$dbh = null;
?>
很多 web 应用程序通过使用到数据库服务的持久连接获得好处。持久连接在脚本结束后不会被关闭,且被缓存,当另一个使用相同凭证的脚本连接请求时被重用。持久连接缓存可以避免每次脚本需要与数据库回话时建立一个新连接的开销,从而让 web 应用程序更快。
Example #4 持久化连接
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
?>
add a note
User Contributed Notes 10 notes
up
down
141
2 years ago
Using PHP 5.4.26, pdo_pgsql with libpg 9.2.8 (self compiled). As usual PHP never explains some critical stuff in documentation. You shouldn't expect that your connection is closed when you set $dbh = null unless all you do is just instantiating PDO class. Try following:
<?php
$pdo = new PDO('pgsql:host=192.168.137.1;port=5432;dbname=anydb', 'anyuser', 'pw');
sleep(5);
$stmt = $pdo->prepare('SELECT * FROM sometable');
$stmt->execute();
$pdo = null;
sleep(60);
?>
Now check your database. And what a surprise! Your connection hangs for another 60 seconds. Now that might be expectable because you haven't cleared the resultset.
<?php
$pdo = new PDO('pgsql:host=192.168.137.160;port=5432;dbname=platin', 'cappytoi', '1111');
sleep(5);
$stmt = $pdo->prepare('SELECT * FROM admin');
$stmt->execute();
$stmt->closeCursor();
$pdo = null;
sleep(60);
?>
What teh heck you say at this point? Still same? Here is what you need to do to close that connection:
<?php
$pdo = new PDO('pgsql:host=192.168.137.160;port=5432;dbname=platin', 'cappytoi', '1111');
sleep(5);
$stmt = $pdo->prepare('SELECT * FROM admin');
$stmt->execute();
$stmt->closeCursor(); // this is not even required
$stmt = null; // doing this is mandatory for connection to get closed
$pdo = null;
sleep(60);
?>
PDO is just one of a kind because it saves you to depend on 3rd party abstraction layers. But it becomes annoying to see there is no implementation of a "disconnect" method even though there is a request for it for 2 years. Developers underestimate the requirement of such a method. First of all, doing $stmt = null everywhere is annoying and what is most annoying is you cannot forcibly disconnect even when you set $pdo = null. It might get cleared on script's termination but this is not always possible because script termination may delayed due to slow client connection etc.
Anyway here is how to disconnect forcibly using postgresql:
<?php
$pdo = new PDO('pgsql:host=192.168.137.160;port=5432;dbname=platin', 'cappytoi', '1111');
sleep(5);
$stmt = $pdo->prepare('SELECT * FROM admin');
$stmt->execute();
$pdo->query('SELECT pg_terminate_backend(pg_backend_pid());');
$pdo = null;
sleep(60);
?>
Following may be used for MYSQL: (not guaranteed)
KILL CONNECTION_ID()
up
down
13
1 year ago
As http://stackoverflow.com/questions/17630772/pdo-cannot-connect-remote-mysql-server points out; sometimes when you want to connect to an external server like this:
<?php
$conn = new PDO('mysql:host=123.4.5.6;dbname=test_db;port=3306','username','password');
?>
it will fail no matter what. However if you put a space between mysql: and host like this:
<?php
$conn = new PDO('mysql: host=123.4.5.6;dbname=test_db;port=3306','username','password');
?>
it will magically work. I'm not sure if this applies in all cases or server setups. But I think it's worth mentioning in the docs.
up
down
27
5 years ago
Just thought I'd add in and give an explanation as to why you need to use 127.0.0.1 if you have a different port number.
The mysql libraries will automatically use Unix sockets if the host of "localhost" is used. To force TCP/IP you need to set an IP address.
up
down
13
7 years ago
To avoid exposing your connection details should you fail to remember to catch any exception thrown by the PDO constructor you can use the following class to implicitly change the exception handler temporarily.
<?php
Class SafePDO extends PDO {
public static function exception_handler($exception) {
// Output the exception details
die('Uncaught exception: ', $exception->getMessage());
}
public function __construct($dsn, $username='', $password='', $driver_options=array()) {
// Temporarily change the PHP exception handler while we . . .
set_exception_handler(array(__CLASS__, 'exception_handler'));
// . . . create a PDO object
parent::__construct($dsn, $username, $password, $driver_options);
// Change the exception handler back to whatever it was before
restore_exception_handler();
}
}
// Connect to the database with defined constants
$dbh = new SafePDO(PDO_DSN, PDO_USER, PDO_PASSWORD);
?>
up
down
8
8 years ago
Note that you can specify a port number with "port=####", but this port number will be ignored if the host is localhost. If you want to connect to a local port other than the default, use host=127.0.0.1 instead of localhost.
up
down
5
3 years ago
If you are using PHP 5.4 and later, you can no longer use persistent connections when you have your own database class that derives from the native PDO object. If you do, you will get segmentation faults during the PHP process shutdown.
Please see this bug report for more information: https://bugs.php.net/bug.php?id=63176
up
down
1
1 year ago
For being able to retrieve information from the db in utf-8 the connection assignment has to add to the dsn `charset=utf8`:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test;charset=utf8', $user, $pass);
?>
up
down
0
2 days ago
If you want to keep connection after fork exit, you can kill with SIGKILL forked process.
<?php
$dbh = new PDO('pgsql:host=localhost;dbname=test', $user, $pass);
$pid = pcntl_fork();
if($pid == 0){
// forked process 'll exit immediately
exit;
}
sleep(1);
$statement = $dbh->query('select 1');
var_dump($statement);
?>
Result: false
<?php
$dbh = new PDO('pgsql:host=localhost;dbname=test', $user, $pass);
$pid = pcntl_fork();
if($pid == 0){
// use sigkill to close process
register_shutdown_function(function(){
posix_kill(getmypid(), SIGKILL);
});
// forked process 'll exit immediately
exit;
}
sleep(1);
$statement = $dbh->query('select 1');
var_dump($statement);
?>
Result: object(PDOStatement)#3 (1) {
["queryString"]=>
string(8) "select 1"
}
up
down
0
20 days ago
I would please advice people who talk about database port in reference with socket files to please read up about what a socket file is. TCP/IP uses ports, a socket file however is a direct pipe line to your database. So no, you should not replace localhost with local ip if you use a different port on your database server, because the socket file has nothing to do with your TCP/IP setup. And whenever possible, using the local socket file is much faster than establishing new TCP/IP connections on each request which is only meant for remote database servers.
up
down
0
5 years ago
On connection errors, the PDO constructor seems to do two things no matter your PDO::ATTR_ERRMODE setting:
1. Trigger a warning
2. Throw a PDOException
If you set the PDO::ATTR_ERRMODE parameter, it will only take effect on further operations.
0 0
- 连接与连接管理
- MySQL 连接与管理
- 连接池管理连接
- 连接管理
- GPRS管理与创建APN拨号连接
- GPRS管理与创建APN拨号连接
- GPRS管理与创建APN拨号连接
- GPRS管理与创建APN拨号连接
- GPRS管理与创建APN拨号连接
- GPRS管理与创建APN拨号连接
- MySql的连接管理与安全性
- ${}与${}连接
- 连接管理(请求/响应)
- 连接池的管理
- 连接池的管理
- 连接池的管理
- Windows mobile 连接管理
- Spring管理JDBC连接
- UML介绍
- java中的字符流、字节流、缓冲流
- github基本操作
- 分片上传(断点续上传)原理
- CS231n:Localization and Detection(定位与检测)
- 连接与连接管理
- sublime text3 浏览器预览设置
- Android属性动画完全解析(上),初识属性动画的基本用法
- 对象建模技术(OMT)方法的应用
- Linux c==网络编程的理论知识-TCP以及UDP数据包的组成(33)
- 免费公开课:讲解DevExpress 2016.2新版本功能
- 面向对象方法
- Nmupy的array切片处理
- 中国第一大财团--大财团谭大才《大财团》--中国第一财团