本文实例讲述了Zend Framework中Zend_Db数据库操作方法。分享给大家供大家参考,具体如下:
引言:Zend操作数据库通过Zend_Db_Adapter
它可以连接多种数据库,可以是DB2数据库、MySQli数据库、Oracle数据库。等等。
只需要配置相应的参数就可以了。
下面通过案例来展示一下其连接数据库的过程。
连接mysql数据库
代码:
点评:
这是连接mysql的代码案例,提供相应的参数就可以了。连接不同的数据库,提供不同的参数。下面是sqlite的例子
代码:
点评:
sqlite明显参数不一样了,只需要提供数据库名字就可以了。
连接完数据库之后,就可以查询数据库信息以及操作数据库信息了。
如果查询呢?
下面是查询的代码案例:
点评:
执行完上述代码,就会展示出数据库中前五条记录的信息。
那么这其中的玄机是什么呢?
我们来看一下源码。
我们来看看Db.php中的factory方法
toArray();
}
/*
* Convert Zend_Config argument to plain string
* adapter name and separate config object.
*/
if ($adapter instanceof Zend_Config) {
if (isset($adapter->params)) {
$config = $adapter->params->toArray();
}
if (isset($adapter->adapter)) {
$adapter = (string) $adapter->adapter;
} else {
$adapter = null;
}
}
/*
* Verify that adapter parameters are in an array.
*/
if (!is_array($config)) {
/**
* @see Zend_Db_Exception
*/
require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception('Adapter parameters must be in an array or a Zend_Config object');
}
/*
* Verify that an adapter name has been specified.
*/
if (!is_string($adapter) || empty($adapter)) {
/**
* @see Zend_Db_Exception
*/
require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception('Adapter name must be specified in a string');
}
/*
* Form full adapter class name
*/
$adapterNamespace = 'Zend_Db_Adapter';
if (isset($config['adapterNamespace'])) {
if ($config['adapterNamespace'] != '') {
$adapterNamespace = $config['adapterNamespace'];
}
unset($config['adapterNamespace']);
}
// Adapter no longer normalized- see http://framework.zend.com/issues/browse/ZF-5606
$adapterName = $adapterNamespace . '_';
$adapterName .= str_replace(' ','_',ucwords(str_replace('_',' ',strtolower($adapter))));
print_r($adapterName);exit;
/*
* Load the adapter class. This throws an exception
* if the specified class cannot be loaded.
*/
if (!class_exists($adapterName)) {
require_once 'Zend/Loader.php';
Zend_Loader::loadClass($adapterName);
}
/*
* Create an instance of the adapter class.
* Pass the config to the adapter class constructor.
*/
$dbAdapter = new $adapterName($config);
/*
* Verify that the object created is a descendent of the abstract adapter type.
*/
if (! $dbAdapter instanceof Zend_Db_Adapter_Abstract) {
/**
* @see Zend_Db_Exception
*/
require_once 'Zend/Db/Exception.php';
throw new Zend_Db_Exception("Adapter class '$adapterName' does not extend Zend_Db_Adapter_Abstract");
}
return $dbAdapter;
}
点评:这个方法就是核心了,代码量不多,但是作用很明确,它会通过你提供的两个参数,自动生成相应的数据库连接类的对象。具有一定的灵活性,机动性。
主要是其中的
这段代码会引入相应的数据库连接类,比如前面的两个例子,就是分别引入了Zend目录下Db目录下Adapter目录下Pdo目录下的mysql.php类。
不同的数据库,会引入不同的数据库文件。
我们来看看mysql.php类中的内容: