一辈挂、以createCommand方式:
// YII2中通過createCommand來處理數(shù)據(jù)庫
// 查詢多條記錄
// {{%user}} 表示如果設(shè)置了表前綴坤次,YII會(huì)自動(dòng)幫你替換
$data1?= YII::$app->db->createCommand('select * from {{%user}}')->queryAll();
// 查詢一條記錄
// createCommand的第二個(gè)參數(shù)可以進(jìn)行參數(shù)綁定
$data2?= YII::$app->db->createCommand('select * from {{%user}} where id=:id', ['id'?=> 2])->queryOne();
// 返回一列(第一列)數(shù)據(jù)
$data3?= YII::$app->db->createCommand('select name from {{%user}}')->queryColumn();
// 返回一個(gè)標(biāo)量值牙捉,常用于統(tǒng)計(jì)
$data4?= YII::$app->db->createCommand('select count(*) as cnt from {{%user}}')->queryScalar();
// 綁定參數(shù)朗若,防止SQL注入問題
// bindValue綁定一個(gè)參數(shù)
$data5?= YII::$app->db->createCommand('select * from {{%user}} where id=:id')
????->bindValue(':id', 3)
????->queryOne();
// 綁定多個(gè)參數(shù)
$data6?= YII::$app->db->createCommand('select * from {{%user}} where id=:id and name=:name')
????->bindValues([':id'?=> 5,?':name'?=>?'eee'])
????->queryOne();
// 綁定參數(shù)引用
$id?= 7;
$data7?= YII::$app->db->createCommand('select * from {{%user}} where id=:id')
????->bindParam(':id',?$id)
????->queryOne();
// 執(zhí)行非查詢語句
$data8?= YII::$app->db->createCommand('update {{%user}} set name=:name where id=:id')
????->bindValues([':name'?=>?'abcdef',?':id'?=> 8])
????->execute();
// 當(dāng)然水孩,我們也可以用更加簡便的方法
// insert()插入
$data9?= YII::$app->db->createCommand()->insert('{{%user}}', [
????'name'?=>?'test',
????'sex'?=> 1,
????'age'?=> 28,
])->execute();
// batchInsert()批量插入
$data10?= YII::$app->db->createCommand()->batchInsert('{{%user}}', ['name',?'sex',?'age'], [
????['111', 1, 11],
????['222', 1, 22],
])->execute();
// update()更新
$data11?= YII::$app->db->createCommand()->update('{{%user}}', [
????'name'?=>?'1242143214'
],?'id=:id', ['id'?=> 10])->execute();
// delete()刪除
$data12?= YII::$app->db->createCommand()->delete('{{%user}}',?'id=:id', ['id'?=> 11])->execute();
// 執(zhí)行事務(wù)
$trans?= YII::$app->db->beginTransaction();
try?{
????YII::$app->db->createCommand()->update('{{%user}}', ['age'?=> 12],?'id=:id', ['id'?=> 13])->execute();
????YII::$app->db->createCommand()->update('{{%user}}', ['age'?=> 22],?'id=:id', ['id'?=> 14])->execute();
????$trans->commit();
}?catch?(\Exception?$e) {
????//如果語句中有一個(gè)執(zhí)行失敗满葛,那么就將回滾
????$trans->rollBack();
????throw?$e;
}
// 獲取表的定義信息
$info?= YII::$app->db->getTableSchema('{{%user}}');