db_insert_word_from_csv_cli.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /*
  3. 生成 巴利原文段落表
  4. */
  5. require_once __DIR__."/../config.php";
  6. require_once __DIR__.'/../public/_pdo.php';
  7. echo "Insert Word To DB".PHP_EOL;
  8. if ($argc != 3) {
  9. echo "help".PHP_EOL;
  10. echo $argv[0]." from to".PHP_EOL;
  11. echo "from = 1-217".PHP_EOL;
  12. echo "to = 1-217".PHP_EOL;
  13. exit;
  14. }
  15. $_from = (int) $argv[1];
  16. $_to = (int) $argv[2];
  17. if ($_to > 217) {
  18. $_to = 217;
  19. }
  20. $dirLog = _DIR_LOG_ . "/";
  21. $dirXmlBase = _DIR_PALI_CSV_ . "/";
  22. $filelist = array();
  23. $fileNums = 0;
  24. $log = "";
  25. define("_DB_", _DB_ENGIN_.":host="._DB_HOST_.";port="._DB_PORT_.";dbname="._DB_NAME_.";user="._DB_USERNAME_.";password="._DB_PASSWORD_.";");
  26. define("_TABLE_", "words");
  27. global $dbh_word_index;
  28. $dns = _DB_;
  29. $dbh_word_index = new PDO($dns, _DB_USERNAME_, _DB_PASSWORD_, array(PDO::ATTR_PERSISTENT => true));
  30. $dbh_word_index->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
  31. if (($handle = fopen(__DIR__."/filelist.csv", 'r')) !== false) {
  32. while (($filelist[$fileNums] = fgetcsv($handle, 0, ',')) !== false) {
  33. $fileNums++;
  34. }
  35. }
  36. if ($_to == 0 || $_to >= $fileNums) {
  37. $to = $fileNums ;
  38. }
  39. for ($from=$_from-1; $from < $_to; $from++) {
  40. echo "doing ".($from+1).PHP_EOL;
  41. #删除
  42. $query = "DELETE FROM "._TABLE_." WHERE book = ?";
  43. $stmt = $dbh_word_index->prepare($query);
  44. $stmt->execute(array($from+1));
  45. if (($fpoutput = fopen(_DIR_CSV_PALI_CANON_WORD_ . "/{$from}_words.csv", "r")) !== false) {
  46. // 开始一个事务,关闭自动提交
  47. $dbh_word_index->beginTransaction();
  48. $query = "INSERT INTO "._TABLE_." ( sn , book , paragraph , wordindex , bold ) VALUES (?,?,?,?,?)";
  49. $stmt = $dbh_word_index->prepare($query);
  50. $count = 0;
  51. while (($data = fgetcsv($fpoutput, 0, ',')) !== false) {
  52. $stmt->execute($data);
  53. $count++;
  54. }
  55. // 提交更改
  56. $dbh_word_index->commit();
  57. if (!$stmt || ($stmt && $stmt->errorCode() != 0)) {
  58. $error = $dbh_word_index->errorInfo();
  59. echo "error - $error[2] ".PHP_EOL;
  60. $log .= "$from, $FileName, error, $error[2] \r\n";
  61. } else {
  62. echo "updata $count recorders.".PHP_EOL;
  63. $log .= "updata $count recorders.\r\n";
  64. }
  65. }
  66. /*
  67. $myLogFile = fopen($dirLog . "insert_index.log", "a");
  68. fwrite($myLogFile, $log);
  69. fclose($myLogFile);
  70. */
  71. }
  72. echo "齐活!功德无量!all done!".PHP_EOL;
  73. ?>