通过循环批量插入随机生成的用户名、性别、年龄记录

来源:互联网 发布:搓碟软件 编辑:程序博客网 时间:2024/06/02 00:43

一、使用单例模式连接数据库:

connDB.php

<?php
/*
 * 连接数据库,使用的是单例模式
 */


class connDB{
private $host = 'localhost';
private $username = 'root';
private $password = '123456';
private $dbname = 'bigdata';
private $tbname = 'user';
private $conn;
private static $instance;

private function __construct() {
//$this->conn = mysql_connect($this->host, $this->username, $this->password, $this->dbname);
$this->conn = mysql_connect($this->host, $this->username, $this->password);
if(!mysql_select_db($this->dbname,$this->conn)){  
echo "失败";  
};  
mysql_query('set names utf8',$this->conn);

return $this->conn;
}//end func construct

public static function singleton() {
if(!isset(self::$instance)){
echo "<BR>单例模式!"; 
//self::$instance = new self();    
$c = __CLASS__;
self::$instance = new $c;
}else{
echo "<BR>已经new过了!";
}
return self::$instance;
}//end func singleton

public function __clone(){
trigger_error('不允许克隆改类!');
}//end func clone

/*
* 执行sql语句
*/
public function query($sql){
$result = mysql_query($sql, $this->conn);
return $result;
}//end func queryLee


}//end class connDB


?>


二、使用循环向数据库中插入数据:

createBigData.php

<?php
/*
 * 向数据库中插入数据,数万级别
 */
set_time_limit(0);
require_once 'connDB.php';
$table = 'user'; //数据库表
$conn = ConnDB::singleton(); //调用单例模式进行数据库操作
//$conns = ConnDB::singleton(); //调用单例模式进行数据库操作
addData($table, $conn);
/*
 * 批量向数据库中插入数据
 */
function addData($table, $conn) {
for($i=1; $i<=100000; $i++){
$name = getName();
$sex = rand(0, 3);
$age = rand(1, 120);
$insert = "insert into ".$table." values( null, $i, '$name', '$sex', '$age')";
$conn->query($insert);
//echo "<BR>insert:".$insert;
}//end for()
}//end func addData()




//随机获取姓名字符串
function getName() {
$name = '';
$singleWord = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$singleWords = 'abcdefghijklmnopqrstuvwxyz';
$length = strlen($singleWord);

for ($i = 0; $i < rand(3, $length); $i++) {
if ($i == 0) {
$name .= substr($singleWord, rand(1, $length)-1, 1);
}else {
$name .= substr($singleWords, rand(1, $length)-1, 1);
}//end if()
}//end for

return $name;
}//end func getName


?>

插入数据之后的查询结果:


结果首页:


与第一条name重复的记录:





0 0
原创粉丝点击