Created
September 24, 2011 12:49
-
-
Save wader/1239299 to your computer and use it in GitHub Desktop.
Output select query as insert statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Output select query as insert statements | |
# | |
# Ex: insert all users from database1 into database2 but replace password with "dummy" | |
# ./mysqlselectdump username database1 "SELECT id, name, \"dummy\" as password FROM users" users password | mysql -u username -ppassword database2 | |
USERNAME="$1" | |
DATABASE="$2" | |
QUERY="$3" | |
INSERTTABLE="$4" | |
PASSWORD="$5" | |
TEMPTABLE="mysqlselectdump_temp_table" | |
if [ "$INSERTTABLE" = "" ] ; then | |
echo "Usage: $0 username database query insert_table [password]" | |
exit | |
fi | |
if [ "$PASSWORD" = "" ] ; then | |
read -s -p "Password: " PASSWORD | |
# write new line on stderr | |
echo 1>&2 | |
fi | |
function q () { | |
mysql -u "$USERNAME" "-p$PASSWORD" -e "$1" "$DATABASE" | |
} | |
q "DROP TABLE IF EXISTS \`$TEMPTABLE\`" | |
q "CREATE TABLE \`$TEMPTABLE\` $QUERY" | |
# dump and replace first temp table name occurence with insert table name | |
# remove --skip-extended-insert if you don't want one insert per line | |
# --complete-insert is important if inserting into existing table | |
mysqldump -u "$USERNAME" "-p$PASSWORD" --skip-extended-insert --skip-triggers --no-create-info --complete-insert "$DATABASE" "$TEMPTABLE" | sed -e "s/$TEMPTABLE/$INSERTTABLE/" | |
q "DROP TABLE IF EXISTS \`$TEMPTABLE\`" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment