quocvuongdn icon

#bash: insert batch data to MySQL

quocvuongdn | PRO | 04/26/17 07:23:09 AM UTC | 0 ⭐ | 334 👁️ | Never ⏰ | []
Bash |

1.17 KB

|

None

|

0 👍

/

0 👎

#!/usr/bin/env bash
echo "Bash version is ${BASH_VERSION}"
 
# Initialize sql query
mysqldb=benchmark
mysqlusr=root
mysqlpwd=root
mysqloptions=""
mysqltable=simple
startSql="INSERT INTO $mysqltable(id, name) VALUES"
 
# Create data list
min=0
max=200000
stepRun=1000
arrSQL=()
 
# Make data as many parts. Max data for single query is step run
for i in $(seq $min $stepRun $max)
do
  childMax=$i
  childMin=$(($childMax-$stepRun))
  sql=$startSql
 
  # Make part sql
  for j in $(seq $childMin $childMax)
  do
    if [ $j -gt $min ]; then
      # Fill row data
      sql="$sql(1, $j)"
      if [ $j -lt $childMax ]; then
        sql="$sql,"
      fi
    fi
  done
 
  # Append part query sql to array
  if [ "$sql" != "$startSql" ]; then
    arrSQL[$i]="$sql;"
  fi
done
 
# Run the query
mysql -u $mysqlusr -p$mysqlpwd $mysqloptions -D $mysqldb -B -e "TRUNCATE $mysqltable"
echo "Table `$mysqltable` has truncated"
echo "Start insert from value $min to value $max"
echo "---------------------------"
 
for i in "${!arrSQL[@]}"
do
  mysql -u $mysqlusr -p$mysqlpwd $mysqloptions -D $mysqldb -B -s -e "${arrSQL[$i]}"
  echo "Added data of index $i"
done

Comments