白驹过隙,这篇文章距今已有一年以上的历史。技术发展日新月异,文中的观点或代码很可能过时或失效,请自行甄别:)

数据库连接配置

配置文件为application/config/database.php,配置文件如下:

$db['default']['hostname'] = "localhost"; //数据库主机名
$db['default']['username'] = "root"; //用户名
$db['default']['password'] = ""; //密码
$db['default']['database'] = "database_name"; //数据库名
$db['default']['dbdriver'] = "mysql"; //数据库类型
$db['default']['port'] = 5432; //数据库端口
$db['default']['dbprefix'] = ""; //数据表前缀
$db['default']['pconnect'] = TRUE; //是否使用持续连接
$db['default']['db_debug'] = FALSE; //显示数据库错误信息
$db['default']['cache_on'] = FALSE; //数据库查询缓存是否打开
$db['default']['cachedir'] = ""; //数据库查询缓存目录所在的服务器绝对路径
$db['default']['char_set'] = "utf8"; //数据库字符集
$db['default']['dbcollat'] = "utf8_general_ci"; //数据库字符规则
$db['default']['swap_pre'] = ""; //默认的dbprefix表前缀(多用于分布式应用)
$db['default']['autoinit'] = TRUE; //数据库类库被载入时是否需要自动连接数据库,为FALSE时会在首次查询时进行连接
$db['default']['stricton'] = FALSE; //是否强制使用“Strict Mode”连接

数据库连接

  1. 自动连接

    $autoload['libraries'] = array('database');//在application/config/autoload.php中添加
  2. 手动连接

    $this->load->database();//常用
    $this->load->database('配置文件中带有配置文件的数组'); //连接到一个制定的数据库
    $this->load->database($dsn);//$dsn=$dsn = 'dbdriver://username:password@hostname/database';当用 DSN 字符串连接时,要覆盖配置默认值,则添加配置变量为查询字符串。$dsn = 'dbdriver://username:password@hostname/database?char_set=utf8&dbcollat=utf8_general_ci&cache_on=true&cachedir=/path/to/cache';
  3. 重新连接

    $this->db->reconnect();
  4. 断开连接

    $this->db->close();

查询数据

$query = $this->db->query('select * from xxx');
/**
 * 获取多条数据
 */
$res = $query->result();//返回一个对象数组(多维)OR空数组,同$query->result_object();
$res = $query->result_array();//返回一个关联数组(多维)OR空数组
/**
 * 获取某条数据
 */
$res = $query->row();//返回第一行数据(对象方式)
$res = $query->row(n);//返回第n行数据,如果n大于数据的条数,则返回第一条的数据
$res = $query->row_array();//同$query->row(),只是返回的数据为关联数组
$res = $query->row_array(n);//同$query->row_array(),返回的是关联数组
$res = $query->first_row();//第一条记录
$res = $query->first_row('array');//返回第一条记录(用数组形式)
$res = $query->last_row();//最后一条记录
$res = $query->last_row('array');//最后一条记录(用数组形式)
$res = $query->next_row();//下一条记录
$res = $query->next_row(‘array');//下一条记录(用数组形式)
$res = $query->previous_row();//上一条记录
$res = $query->previous_row('array');//上一条记录(用数组形式)

辅助函数

查询

$query->num_rows(); //查询结果集的行数
$query->num_fields(); //返回当前请求的字段数目(即列数)
$query->free_result(); //释放结果集

其它

$this->db->insert_id();//执行数据插入时的ID
$this->db->affected_rows();//影响的行数
$this->db->count_all('table_name');//返回某个表的总行书
$this->db->platform();//数据库平台(mysql,MS SQL...)
$this->db->version();//数据库版本
$this->db->last_query();//最近一次查询
$this->db->insert_string('table_name' , $data); //生成标准的insert语句
$this->db->update_string('table_name' , $data); //生成标准的update语句

AR模式(Active Record模式):推荐,简洁&&安全

新增数据

$this->db->insert( 'table1' , $data ); //向table1表插入$data数据,$data为关联数组或者对象
$this->db->insert_batch( 'table1' , $data ); //向table1表插入多条数据,$data为二维数组

更新数据

//更新一条
$this->db->where('id' , $id); //更新的条件(可选),如果有多个条件,则多条where语句
$this->db->update('table' , $data);//$data为要更新的关联数组
//更新多条
$this->db->update_batch('table' , $data);//$data为要更新的多条数据,二维关联数组

删除数据

//删除一张表中的记录
$this->db->delete('table1' , array('id' => $id) );//删除table1表中id为$id的记录
//删除多个表中的的同一个条件的数据
$tables = array('table1','table2','table3');
$this->db->where('id' , $id );
$this->db->delete($tables);
//清空表
$this->db->empty_table('table1');//清空table1表

查询数据

$query = $this->db->get('table1');//select * from table1
$query = $this->db->get('table1' , $limit , $offset );//select * from table1 limit $list,$offset 注意返回的是结果集,如果需要数据可以用$query->result()等来获取
$query = $this->db->get_where('table1',array('id=>$id),$limit,$offset);//select * from tables where id=$id limit $limit,$offset,返回的是结果集,需要数据用$query->result()等来获取

查询条件

$this->db->select('field1','field2','field3');//select条件
$this->db->select_max('field');//SELECT MAX(field)
$this->db->select_min('field');//SELECT MIN(field)
$this->db->select_avg('field');//SELECT AVG('field);
$this->db->select_sum('field');//SELECT SUM('field');
$this->db->from('table1');SELECT * FROM table1
$this->db->join('table2','table2.id=table1.uid','left/right/outer/inner/left outer/right outer');//XX JOIN table2 ON table2.id=table1.uid
/**
 * where查询
 */
1. $this->db->where('id' , $id);//简单的key/value形式,多次调用会将where条件用AND连接起来
2. $this->db->where('id!=' , $id);//自定义条件,可以用>=,<=,=,!=等符号
3. $this->db->where(array(
        'name>' => $name,
        'id<='  => $id
    ));//关联数组形式
4. $this->db->where('name="abc" AND status="1"');//自定义形式

$this->db->or_where();//同上面的where,只是条件使用OR连接起来
$this->where_in('id' , $in_condition);//WHERE field IN('a','b')语句
$this->db->or_where_in();//同上,只是会用OR将它与其他where语句连接起来
$this->db->where_not_in();//WHERE field NOT IN('item1','item2');
$this->db->or_where_not_in('id',$id_conditions);//WHERE id NOT IN('item1','item2')

/**
 * like语句
 */
1. $this->db->like('id' , 'value'); //简单的key/value形式
2. $this->db->like(array(
        'title' => $title,
        'name'  => $name
    ));//关联数组形式

$this->db->or_like();//用法同like,只是多个条件时用OR连接
/**
 * not like语句
 */
$this->db->not_like('id','value');//简单的key/value形式
$this->db->not_like(array(
    'title' => $title,
    'name' => $name
));//关联数组形式

$this->db->or_not_like();//用法通not like,只是多个条件时用OR连接

$this->db->group_by('xxx');   //GROUP BY xxx
$this->db->distinct();       // SELECT DISTINCT ...
/**
 * having语句
 */
$this->db->having('id=45');
$this->db->having('id',45);
$this->db->having(array(
    'title=' => 'xxx',
    'id<'    => $id
));
$this->db->or_having();//同having(),多个子句用OR分隔

/**
 * order by
 */
$this->db->order_by('title','desc');
$this->db->order_by('title desc , name asc'); //可用排序desc,asc,random(Oracle,MSSQL不支持)

/**
 * limit
 */
$this->db->limit(10);  //LIMIT 10
$this->db->limit(20,10); //LIMIT 20,10(仅限MYSQL)

$this->db->count_all_results();//获取AR查询所返回的结果数量

AR缓存

$this->db->start_cache();//开启缓存
$this->db->stop_cache();//关闭缓存
$this->db->flush_cache();//清空缓存

事务支持

/**
 * 自动执行(此模式途中的sql如果遇到错误自动回callback,如果成功自动commit
 */
$this->db->trans_start();  //开启自动事务
....//各种sql执行
$this->db->trans_complete();//自动事务关闭

/**
 * 手动执行(此模式中sql需要错误需要callback以及成功自动commit需要自己手动操作
 */
$this->db->trans_begin(); //开启手动事务
...//各种sql执行
if ($this->db->trans_status() === FALSE) {
    $this->db->trans_rollback(); //遇到错误手动rollback
}
$this->db->commit(); //提交

/**
 * 严格模式(启动时如果正在运行很多组的事务(CI事务中默认开启此模式),那么如果只要有一组失败,所有组都将会被回滚.而如果被禁用,那么每一组都视为独立的组,意味着其中一个组失败不会影响其他组)
 */
$this->db->trans_strict(TRUE);//TRUE=>开启,FALSE=>关闭

/**
 * 禁用事务(所有query自动提交)
 */
$this->db->trans_off();

/**
 * 测试模式(将导致你的查询被回滚,虽然查询会生成有效结果)
 */
$this->db->trans_start(TRUE);

/**
 * 管理错误信息
 */
if($this->db->trans_status() === FALSE) {
 //do something
}