在實(shí)際工作中, 一般都是一條一條的插入數(shù)據(jù), 但有時(shí)也會(huì)有很多的數(shù)據(jù), 如果還是通過(guò)循環(huán)一條條插入, 效率就低了好多, 這時(shí)我們最好使用批量插入數(shù)據(jù)的方法
1. 原生方法
INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
2. CI框架查詢構(gòu)造器類
$data = array(
array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
),
array(
'title' => 'Another title',
'name' => 'Another Name',
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
3. TP框架方法:
$data = [
[ 'title' => 'My title','name' => 'My Name','date' => 'My date'],
[ 'title' => 'Another title','name' => 'Another Name','date' => 'Another date'],
];
Db::name('mytable')->insertAll($data);
不管是你是使用原生的SQL,還是使用各個(gè)PHP框架, 都是有對(duì)應(yīng)的批量插入方法的, 適當(dāng)?shù)臅r(shí)候不要忘記使用喲, 這會(huì)大大提升代碼的執(zhí)行效率的