<?php class Sql { private $db; //连接数据库 function __construct($char = 'utf8') { try { $dsn = 'mysql:dbname=test;host=127.0.0.1'; $user = 'root'; $password = '123123'; $this->db = new PDO($dsn, $user, $password); $this->db->query("set names $char"); } catch (Exception $e) { exit($e->getMessage()); } } //获取信息 public function getinfo() { echo "数据库服务信息:" . $this->db->getAttribute(PDO::ATTR_SERVER_INFO) . "<br>"; //数据库服务信息 echo "服务信息:" . $this->db->getAttribute(PDO::ATTR_SERVER_VERSION) . "<br>"; //服务器版本 echo "客户端信息:" . $this->db->getAttribute(PDO::ATTR_CLIENT_VERSION) . "<br>"; //客户端信息 echo "连接信息:" . $this->db->getAttribute(PDO::ATTR_CONNECTION_STATUS) . "<br>"; //连接信息 } //设置错误提示模式 public function seterr($err = 'EXCEPTION') { switch ($err) { case 'SILENT': $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT); break;//仅设置错误代码。 case 'WARNING': $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); break;//引发 E_WARNING 错误 default: $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //echo '不合法的设置,系统默认设置为ERRMODE_EXCEPTION'; break;//抛出 exceptions 异常 } } public function geterr() { return $this->db->errorInfo(); } //执行语句 public function query($sql, $param) { @$zj = $this->db->prepare($sql); @$zid = $zj->execute($param); return $zid; } //查询 public function select($sql, $arr) { // echo $sql.'===='.json_encode($arr).'<br>'; @$zj = $this->db->prepare($sql); @$zid = $zj->execute($arr); @$zsd = $zj->fetchAll(); return $zsd; } //批次查询 //插入 public function insert($sql, $arr) { $zj = $this->db->prepare($sql); $zid = $zj->execute($arr); return $zid; } //修改 public function update($sql, $arr) { $zj = $this->db->prepare($sql); @$zid = $zj->execute($arr); return $zid; } //删除 public function delete($sql, $arr) { //$sql = "delete from $tbname where $term"; $zj = $this->db->prepare($sql); @$zid = $zj->execute($arr); return $zid; } //开启事务 public function startwork() { $this->db->setAttribute(PDO::ATTR_AUTOCOMMIT, 0); ###//关闭自动提交 $this->db->beginTransaction(); #####//开启事务 } //执行事务 public function exwork() { $this->db->commit(); //执行整个事务 $this->db->setAttribute(PDO::ATTR_AUTOCOMMIT, 1); //开启自动提交 } //回滚事务 public function rollwork() { $this->db->rollback(); //撤销全部事务 $this->db->setAttribute(PDO::ATTR_AUTOCOMMIT, 1); //开启自动提交 } //关闭连接 public function close() { $this->db = null; } function sel() { $sel = $this->db->query('select * from root where user = "root"'); $rst = $sel->fetchAll(); } } function createString($len){ $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ'; $key = ''; for($i=0;$i<$len;$i++) { $key .= $pattern[mt_rand(0,35)]; //生成php随机数 } return $key; } $db = new Sql(); for ($i=0; $i < 100000 ; $i++) { $data = [ null, createString(mt_rand(8,12)), md5(createString(8)), mt_rand(0,1), createString(6).'@'.createString(3).'.'.createString(3), mt_rand(3,120), mt_rand(50,18888)*mt_rand(50,18888) ]; $db->insert('INSERT INTO user VALUES (?,?,?,?,?,?,?)',$data); } echo 'ok';