用查询生成器产生CRUD–kohana3使用手册
Kohana 3.0 数据查询生成器能为你的数据库简单的创建 CRUD 语句(CRUD = Create Read Update Delete就是数据库的基本操作创建,读取,更新,删除)。
这里的示例使用了下面的数据库结构
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL auto_increment,
`username` varchar(30) NOT NULL,
`password` varchar(40) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
创建数据库记录
创建数据库记录需要使用 DB::insert() 方法。这个请求的基本格式如下。
DB::insert(‘table_name’, array(‘column’))->values(array(‘column_value’))->execute();
如果命令成功,你就能得到一个包含 insert_id 和 total_rows (总共影响到的行数)组成的数组
用法
在 try/catch 块中执行调用,那么你就能捕捉到异常。
try
{
list($insert_id, $total_rows) = DB::insert('users', array('username','password'))
->values(array('myusername',sha1('mypassword')))
->execute();
echo $insert_id .' '.$total_rows ;
}
catch ( Database_Exception $e )
{
echo $e->getMessage();
}
读取数据库记录
读取数据库记录需要使用到 DB::select() 方法。这个请求的基本格式如下
// 返回一个结果对象
$result = DB::select('column')->from('table_name')->execute();
// 结果作为数组返回
$result = DB::select('column')->from('table_name')->execute()->as_array();
// 结果作为标准类对象返回s
$result = DB::select('column')->from('table_name')->as_object()->execute();
// 仅返回第一行
$result = DB::select('column')->from('table_name')->execute()->current();
你可以按你所需要的在上面的示例中选择一个方法。
// 返回一个列
$result = DB::select('column')->from('table_name')->execute()->current();
//返回3列
$result = DB::select('column', 'column2', 'column3')->from('table_name')->execute()->current();
// 列名的别名
$result = DB::select(array('longcolumnname1', 'col1'), array('longcolumnname2', 'aliascol2'))->from('table_name')->execute()->current();
你可以用 where() 方法来选择特定的记录
$result = DB::select()->from(‘table_name’)->where(‘column’,'=’,'value’)->execute();
有多种多样的方法可用来 构建复杂的 SELECT 语句。查看 API 文档来了解更多细节
用法
在 try/catch 块中执行调用,那么你就能捕捉到异常。
public function action_select()
{
try
{
$user = DB::select()->from('users')
->where('id','=', $this->request->param('id'))
->execute()->current();
echo Kohana::debug($user);
}
catch( Database_Exception $e )
{
echo $e->getMessage();
}
}
更新数据库记录
更新数据库记录需要用到 DB::update() 方法. 这个请求的基本格式如下
$total_rows = DB::update(‘table_name’)->set(array(‘column’=>’value’))->where(‘column’,'=’,'value’)->execute();
如果命令成功,你就能得到结果中影响到的行数
用法
在 try/catch 块中执行调用,那么你就能捕捉到异常。
try
{
$total_rows = DB::update('users')->set(array('username'=>'newuser'))
->where('id','=',2)->execute();
echo Kohana::debug($total_rows);
}
catch( Database_Exception $e )
{
echo $e->getMessage();
}
删除数据库记录
删除数据库记录需要用到 DB::delete() 方法。这个请求的基本格式如下
$total_rows = DB::delete(‘table_name’)->where(‘column’,'=’,'value’)->execute();
如果命令成功,你就能得到结果中影响到的行数
用法
在 try/catch 块中执行调用,那么你就能捕捉到异常。
try
{
$total_rows = DB::delete('users')->where('id','=',2)->execute();
echo Kohana::debug($total_rows);
}
catch( Database_Exception $e )
{
echo $e->getMessage();
}