Create table if not exists from mysqldump

前端 未结 8 1121
一整个雨季
一整个雨季 2020-12-29 21:35

I\'m wondering if there is any way in mysqldump to add the appropriate create table option [IF NOT EXISTS]. Any ideas?

相关标签:
8条回答
  • 2020-12-29 22:01

    To Find and replace the text On Windows 7 Using PowerShell

    Open command prompt and use the command below

    powershell -Command "(gc E:\map\map_2017.sql) -replace 'CREATE TABLE', 'CREATE TABLE IF NOT EXISTS' | Out-File E:\map\map_replaced.sql"
    
    • First param is the filepath

    • Second param is 'find string'

    • Third param is 'replace string'

    This command will create a new file with the replaced text. Remove the Command starting from '|' (pipe) if you want to replace and save contents on the same file.

    0 讨论(0)
  • 2020-12-29 22:02

    The dump output is the combination of DROP and CREATE, so you must remove DROP statement and change the CREATE statement to form a valid (logical) output:

     mysqldump --no-data -u root <schema> | sed 's/^CREATE TABLE /CREATE TABLE IF NOT EXISTS /'| sed 's/^DROP TABLE IF EXISTS /-- DROP TABLE IF EXISTS /' > <schema>.sql
    
    0 讨论(0)
  • 2020-12-29 22:07

    Using sed as described by @Pawel works well. Nevertheless you might not like the idea of piping your data through more potential error sources than absolutely necessary. In this case one may use two separate dumps:

    • first dump containing table definitions (--no-data --skip-add-drop-table)
    • second dump with only data (--no-create-info --skip-add-drop-table)

    There are some other things to take care of though (e.g. triggers). Check the manual for details.

    0 讨论(0)
  • 2020-12-29 22:14

    Try to use this on your SQL file:

    sed 's/CREATE TABLE/CREATE TABLE IF NOT EXISTS/g' <file-path>
    

    or to save

    sed -i 's/CREATE TABLE/CREATE TABLE IF NOT EXISTS/g' <file-path>
    

    it's not ideal but it works :P

    0 讨论(0)
  • 2020-12-29 22:15

    According to one source, mysqldump does not feature this option.

    You could use the --force option when importing the dump file back, where MySQL will ignore the errors generated from attempts to create duplicate tables. However note that with this method, other errors would be ignored as well.

    Otherwise, you can run your dump file through a script that would replace all occurrences of CREATE TABLE with CREATE TABLE IF NOT EXISTS.

    0 讨论(0)
  • 2020-12-29 22:18

    The sed will be much faster without the 'g' (global) at its end:

    eg:

    mysqldump -e <database> | sed 's/^CREATE TABLE /CREATE TABLE IF NOT EXISTS /' > <database>.sql 
    
    0 讨论(0)
提交回复
热议问题