使用php将大量数据插入mysql

时间:2011-12-05 20:48:39

标签: php mysql

我想生成随机字符串并插入数据库,插入应该是高效且健壮的。我有一个像这样工作的生成字符串函数:

public function getRandString(){
    $string= //generats a random string
    return $string;
}

db connection:

$con = mysql_connect($host, $user, $pass)
or die ( " Not able to connect to server ");
mysql_select_db($db_name);

现在我想创建一个方法,将随机字符串一次插入数据库1个行,每行包含2列随机字符串,我应该怎么做呢?

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

最好在数据库端创建随机字符串函数,并运行一次INSERT ... SELECT查询以生成行。

答案 1 :(得分:1)

两种方法:

  1. 使用php创建一个sql文件,通过命令行,phpmyadmin,sequelpro,tomcat等导入

    • 打开文件
    • 追加INSERT INTO whatever VALUES ( 'randomshit', 'randomshit' );,无论多少次
    • 关闭文件,使用它填充db
  2. 使用上面提到的连接:

    • 分批创建INSERT INTO whatever VALUES( 'randomshit', 'randomshit' ); 25000

      $howMany = 40;
      // do this 40 times (40x25000 ) = 1,000,000
      while( --$howmany ) {
        $random = "";
        $randomMany = 25000;
        while( --$randomMany ) {
          $random += sprintf( "INSERT INTO whatever VALUES ('%s', '%s'); ", rand_text(), rand_text() );
        }
        // you'll now have a big list (25000 ) of insert queries to insert
        mysql_query( $random );
      }
      

答案 2 :(得分:0)

我们可以结合两个技巧来生成一个垃圾表:

创建一位数字表:https://stackoverflow.com/a/273703/260007

CREATE TABLE num (i int);
INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);

生成随机字符串:

INSERT INTO junktable
SELECT
  (SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 6)) AS aa,
  (SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 6)) AS bb
FROM       num AS l1
INNER JOIN num AS l2
INNER JOIN num AS l3
INNER JOIN num AS l4
INNER JOIN num AS l5
INNER JOIN num AS l6
LIMIT 100; -- number of wanted rows