[英]Multi-valued INSERT for SQLite3 using PDO
我目前正在嘗試對SQLite3和PDO使用多值INSERT查詢。
我進行了一些研究,發現在SQLite版本3.7.11之前,不支持多值INSERT語法。 自2012年以來,情況發生了變化。
我的phpinfo()通知我:
PDO Driver for SQLite 3.x enabled
SQLite Library 3.7.7.1
無論如何,PDO似乎不支持通過SQLite3使用這類INSERT查詢。
我的問題是此問題是否有解決方法。 我正在與SQLite3和MySQL兼容的應用程序上工作。 看到它們都支持多值插入,我討厭只因為PDO不是最新的而使用兩種查詢和INSERT邏輯。
一些編輯-添加代碼細節:
打開數據庫連接:
public function useSQLite3($file)
{
$dsn = "sqlite:$file";
$this->dbService = new PDO ($dsn);
$this->dbService->query('PRAGMA journal_mode=WAL;');
$this->dbService->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
處理批量插入數據庫的方法:
public function bulkInsertLink(array $links)
{
$insertRows = array();
$placeholders = array();
$j = 0;
$i=0;
foreach($links as $linkData) {
$placeholders[$j] = '(';
foreach($linkData as $columnData) {
$placeholders[$j] .= '?,';
$insertRows[$i] = $columnData;
$i++;
}
$placeholders[$j] = rtrim($placeholders[$j], ',');
$placeholders[$j] .= ')';
$j++;
}
$query = 'INSERT INTO links (status, date, lang, group_ID, group_link_ID, link, sitemap_link) VALUES ';
$query .= implode(',', $placeholders);
$preparedQuery = $this->dbService->prepare($query);
$preparedQuery->execute($insertRows);
}
$ links是一個數組,其中每個元素代表要插入的一行的信息。
使用PDO,您可以像這樣進行多值插入:
$statement = $pdo->prepare('INSERT INTO t VALUES (?, ?), (?, ?)');
$pdo->execute([1, 2, 3, 4]);
但是我親自准備了一個插入語句,並使用不同的參數多次執行了它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.