A-A+

php读取txt文件并将数据插入到数据库

2019年12月08日 我爱编程 暂无评论

今天测试一个功能,需要往数据库中插入一些原始数据,PM给了一个txt文件,如何快速的将这个txt文件的内容拆分为所要的数组,然后再插入到数据库中?

serial_number.txt的示例内容:

serial_number.txt:

  1. DM00001A11 0116,
  2. SN00002A11 0116,
  3. AB00003A11 0116,
  4. PV00004A11 0116,
  5. OC00005A11 0116,
  6. IX00006A11 0116,

创建数据表:

  1. create table serial_number(
  2. id int primary key auto_increment not null,
  3. serial_number varchar(50) not null
  4. )ENGINE=InnoDB DEFAULT CHARSET=utf8;

php代码如下:

  1. $conn = mysql_connect('127.0.0.1','root',''or die("Invalid query: " . mysql_error());
  2. mysql_select_db('test'$connor die("Invalid query: " . mysql_error());
  3. $content = file_get_contents("serial_number.txt");
  4. $contentsexplode(",",$content);//explode()函数以","为标识符进行拆分
  5. foreach ($contents as $k => $v)//遍历循环
  6. {
  7.   $id = $k;
  8.   $serial_number = $v;
  9.   mysql_query("insert into serial_number (`id`,`serial_number`)
  10.       VALUES('$id','$serial_number')");
  11. }

备注:方法有很多种,我这里是在拆分txt文件为数组后,然后遍历循环得到的数组,每循环一次,往数据库中插入一次。

再给大家分享一个支持大文件导入的:

  1. <?php
  2. /**
  3.  * $splitChar 字段分隔符
  4.  * $file 数据文件文件名
  5.  * $table 数据库表名
  6.  * $conn 数据库连接
  7.  * $fields 数据对应的列名
  8.  * $insertType 插入操作类型,包括INSERT,REPLACE
  9.  */
  10. function loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields=array(),$insertType='INSERT'){
  11.   if(emptyempty($fields)) $head = "{$insertType} INTO `{$table}` VALUES('";
  12.   else $head = "{$insertType} INTO `{$table}`(`".implode('`,`',$fields)."`) VALUES('";  //数据头
  13.   $end = "')";
  14.   $sqldata = trim(file_get_contents($file));
  15.   if(preg_replace('/\s*/i','',$splitChar) == '') {
  16.     $splitChar = '/(\w+)(\s+)/i';
  17.     $replace = "$1','";
  18.     $specialFunc = 'preg_replace';
  19.   }else {
  20.     $splitChar = $splitChar;
  21.     $replace = "','";
  22.     $specialFunc = 'str_replace';
  23.   }
  24.   //处理数据体,二者顺序不可换,否则空格或Tab分隔符时出错
  25.   $sqldata = preg_replace('/(\s*)(\n+)(\s*)/i','\'),(\'',$sqldata);  //替换换行
  26.   $sqldata = $specialFunc($splitChar,$replace,$sqldata);        //替换分隔符
  27.   $query = $head.$sqldata.$end;  //数据拼接
  28.   if(mysql_query($query,$conn)) return array(true);
  29.   else {
  30.     return array(false,mysql_error($conn),mysql_errno($conn));
  31.   }
  32. }
  33. //调用示例1
  34. require 'db.php';
  35. $splitChar = '|';  //竖线
  36. $file = 'sqldata1.txt';
  37. $fields = array('id','parentid','name');
  38. $table = 'cengji';
  39. $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields);
  40. if (array_shift($result)){
  41.   echo 'Success!<br>';
  42. }else {
  43.   echo 'Failed!--Error:'.array_shift($result).'<br>';
  44. }
  45. /*sqlda ta1.txt
  46. 1|0|A
  47. 2|1|B
  48. 3|1|C
  49. 4|2|D
  50. -- cengji
  51. CREATE TABLE `cengji` (
  52.  `id` int(11) NOT NULL AUTO_INCREMENT,
  53.  `parentid` int(11) NOT NULL,
  54.  `name` varchar(255) DEFAULT NULL,
  55.  PRIMARY KEY (`id`),
  56.  UNIQUE KEY `parentid_name_unique` (`parentid`,`name`) USING BTREE
  57. ) ENGINE=InnoDB AUTO_INCREMENT=1602 DEFAULT CHARSET=utf8
  58. */
  59. //调用示例2
  60. require 'db.php';
  61. $splitChar = ' ';  //空格
  62. $file = 'sqldata2.txt';
  63. $fields = array('id','make','model','year');
  64. $table = 'cars';
  65. $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields);
  66. if (array_shift($result)){
  67.   echo 'Success!<br>';
  68. }else {
  69.   echo 'Failed!--Error:'.array_shift($result).'<br>';
  70. }
  71. /* sqldata2.txt
  72. 11 Aston DB19 2009
  73. 12 Aston DB29 2009
  74. 13 Aston DB39 2009
  75. -- cars
  76. CREATE TABLE `cars` (
  77.  `id` int(11) NOT NULL AUTO_INCREMENT,
  78.  `make` varchar(16) NOT NULL,
  79.  `model` varchar(16) DEFAULT NULL,
  80.  `year` varchar(16) DEFAULT NULL,
  81.  PRIMARY KEY (`id`)
  82. ) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8
  83. */
  84. //调用示例3
  85. require 'db.php';
  86. $splitChar = '  ';  //Tab
  87. $file = 'sqldata3.txt';
  88. $fields = array('id','make','model','year');
  89. $table = 'cars';
  90. $insertType = 'REPLACE';
  91. $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields,$insertType);
  92. if (array_shift($result)){
  93.   echo 'Success!<br>';
  94. }else {
  95.   echo 'Failed!--Error:'.array_shift($result).'<br>';
  96. }
  97. /* sqldata3.txt
  98. 11  Aston  DB19  2009
  99. 12  Aston  DB29  2009
  100. 13  Aston  DB39  2009 
  101. */
  102. //调用示例3
  103. require 'db.php';
  104. $splitChar = '  ';  //Tab
  105. $file = 'sqldata3.txt';
  106. $fields = array('id','value');
  107. $table = 'notExist';  //不存在表
  108. $result = loadTxtDataIntoDatabase($splitChar,$file,$table,$conn,$fields);
  109. if (array_shift($result)){
  110.   echo 'Success!<br>';
  111. }else {
  112.   echo 'Failed!--Error:'.array_shift($result).'<br>';
  113. }
  114. //附:db.php
  115. /*  //注释这一行可全部释放
  116. ?>
  117. <?php
  118. static $connect = null;
  119. static $table = 'jilian';
  120. if(!isset($connect)) {
  121.   $connect = mysql_connect("localhost","root","");
  122.   if(!$connect) {
  123.     $connect = mysql_connect("localhost","Zjmainstay","");
  124.   }
  125.   if(!$connect) {
  126.     die('Can not connect to database.Fatal error handle by /test/db.php');
  127.   }
  128.   mysql_select_db("test",$connect);
  129.   mysql_query("SET NAMES utf8",$connect);
  130.   $conn = &$connect;
  131.   $db = &$connect;
  132. }
  133. ?>

复制代码,-- 数据表结构:

  1. -- 100000_insert,1000000_insert
  2. CREATE TABLE `100000_insert` (
  3.  `id` int(11) NOT NULL AUTO_INCREMENT,
  4.  `parentid` int(11) NOT NULL,
  5.  `name` varchar(255) DEFAULT NULL,
  6.  PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
  8. 100000 (10万)行插入:Insert 100000_line_data use 2.5534288883209 seconds
  9. 1000000(100万)行插入:Insert 1000000_line_data use 19.677318811417 seconds
  10. //可能报错:MySQL server has gone away
  11. //解决:修改my.ini/my.cnf max_allowed_packet=20M
标签:

给我留言

Copyright © 四季博客 保留所有权利.   Theme  Ality

用户登录