php鏈接數據庫 半年后需要更換MySQL為集群模式或者有錢了升級oracl數據庫,這時的改動相當大,成本高。如果再之前使用PDO,之后再遇見這樣的問題就很輕松。
開啟PDO:
打開php.ini文件,將需要打開的dll擴展件前面的“;”去掉。
;extension=php_pdo_firebird.dll
;extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
;extension=php_pdo_odbc.dll
測試能否使用
打開php.info()查看到:

使用語法
$db->setAttribute(PDO::ATTR_CASE, PDO::CASE_UPPER);$rs = $db->query("SELECT * FROM foo");$rs->setFetchMode(PDO::FETCH_ASSOC);$result_arr = $rs->fetchAll();PRint_r($result_arr);
setAttribute():
PDO::CASE_LOWER -- 強制列名是小寫
PDO::CASE_NATURAL -- 列名按照原始的方式
PDO::CASE_UPPER -- 強制列名為大寫
setFetchMode():
PDO::FETCH_ASSOC -- 關聯數組形式
PDO::FETCH_NUM -- 數字索引數組形式
PDO::FETCH_BOTH -- 兩者數組形式都有,這是缺省的
PDO::FETCH_OBJ -- 按照對象的形式,類似于以前的 mysql_fetch_object()
異常處理:
try{ $db = new PDO($dsn,$user,$passwd);}catch(PDOException $e){ print $e->getMessage(); // 返回異常信息 print $e->getCode(); // 返回異常代碼 print $e->getFile(); // 返回發生異常的文件名 print $e->getLine(); // 返回發生異常的代碼行號 print $e->getTrace(); // backtrace() 數組 print $e->getTraceAsString(); // 已格成化成字符串的 getTrace() 信息 }$count = $db->exec("insert into info_u set name,nickname ='hefe',job=1;");print $db->errorCode();print_r($db->errorinfo());--------------------------------------------------
[message:protected] => SQLSTATE[HY000] [1045] access denied for user 'coffee'@'localhost' (using passWord: YES)
[string:Exception:private] =>
[code:protected] => 1045
[file:protected] => /alidata/www/webpage/signup.php
[line:protected] => 11
[trace:Exception:private] => Array
(
[0] => Array
(
[file] => /alidata/www/webpage/signup.php
[line] => 11
[function] => __construct
[class] => PDO
[type] => ->
[args] => Array
(
[0] => mysql:host=localhost;dbname=fengchao
[1] => coffee
[2] => coffe
)
)
)
[previous:Exception:private] =>
[errorInfo] =>
42S22
Array( [0] => 42S22 [1] => 1054 [2] =>Unknown column 'name' in 'field list' )
在new新的鏈接時,異常處理用PDOException();在執行exection()時異常處理使用errorInfo()和errorCode();
errorCode()返回:
00000 //執行正常
1054 //Unknown column 'X' in 'field list' 字段X未出現在在字段中
1110 // 字段出現兩次出現兩次
1062 //Duplicate entry 'X' for key 'PRIMARY' 重復主鍵
......
新聞熱點
疑難解答