<?php
// sqlite操作类
class SqliteDBHelper{
public function __construct(){
// 初始化数据库,并且连接数据库 数据库配置
$this->db = new PDO('sqlite:'.dirname(__FILE__).'\log.db');
$this->init();
}
public function init()
{
# 表初始化,创建表
$this->db->exec("CREATE TABLE log(
id integer PRIMARY KEY autoincrement,
pagelinks varchar(200),
ip varchar(200),
datetimes datetime default (datetime('now', 'localtime'))
)");
}
public function insert($tab_name)
{
try{
//开启事物,此时会关闭自动提交
$this->db->beginTransaction();
$sql = "INSERT INTO ".$tab_name." (id,pagelinks,ip) values (?,?,?)";
$stmt = $this->db->prepare($sql);
$s=0;
//大批量插入
while($s <= 99999){
$stmt->execute(array(null,"http://www.zhangkang.com.cn/".$s,"w"));
$s++;
}
//提交事物,并且数据库连接返回到自动提交模式
$this->db->commit();
}
catch(PDOException $e)
{
echo '执行失败'.$e->getMessage();
}
}
public function query($tab_name,$where='')//表名称和条件
{
$sth = $this->db->prepare('SELECT * FROM '.$tab_name.' '.$where);
$sth->execute();
$result = $sth->fetchAll();
return $result;
}
}
$db=new SqliteDBHelper();
$res=$db->insert('log');//批量插入
$res=$db->query('log',"limit 100");//查询
foreach($res as $key => $row) {
echo $row['pagelinks']."<br/>";
}
?> 版权声明:《 PHP如何使用事务大幅提高批量写入SQLite数据库的速度 》为zhangkang原创文章,转载请注明出处!
最后编辑:2019-5-10 19:05:35