Bash script to insert values in MySQL

后端 未结 5 858
别跟我提以往
别跟我提以往 2020-11-30 07:48

I want to make a bash script that connects to my MySQL server and inserts some valuse from a txt file. I have written this down:

#!/bin/bash
echo \"INSERT I         


        
相关标签:
5条回答
  • 2020-11-30 08:20

    Try this one:

    #!/bin/bash
    inputfile="test.txt"
    cat $inputfile | while read ip mac server; do
        echo "INSERT INTO test (IP,MAC,SERVER) VALUES ('$ip', '$mac', '$server');"
    done | mysql -uroot -ptest test;
    

    This way you streaming the file read as well the mysql comand execution.

    0 讨论(0)
  • 2020-11-30 08:25
    #!/bin/bash
    
    username=root
    password=root
    dbname=myDB
    host=localhost
    TS=$(date +%s)
    
    echo $1
    mysql -h$host -D$dbname -u$username -p$password -e"INSERT INTO dailyTemp (UTS, tempF) VALUES ($TS, $1);"
    
    exit 0 
    
    0 讨论(0)
  • 2020-11-30 08:32

    Assuming you have many rows to add, you probably need LOAD DATA INFILE statement, not INSERT. The source file has to be on the server, but it seems to be the case here.

    Something like that:

    #!/bin/bash
    
    mysql -uroot -ptest test << EOF
    
    LOAD DATA INFILE 'test.txt'
        INTO TABLE tbl_name
        FIELDS TERMINATED BY ' ';
    
    EOF
    

    LOAD DATA INFILE has many options as you will discover by reading the doc.

    0 讨论(0)
  • 2020-11-30 08:32

    You are trying to insert the value "cat test.txt" as a String in the database in an INSERT statement that requires 3 parameters (IP,MAC and SERVER) so this is why you get this error message.

    You need to read the text file first and extract the IP, MAC and Server values and then use these in the query that would look like this once filled :

    #!/bin/bash
    echo "INSERT INTO test (IP,MAC,SERVER) VALUES ('10.16.54.29', '00:f8:e5:33:22:3f', 'marsara');" | mysql -uroot -ptest test;
    
    0 讨论(0)
  • 2020-11-30 08:32

    I use this and it works:

    mysql -uroot -proot < infile
    

    or select the database first

    ./mysql -uroot -proot db_name < infile
    

    or copy the whole SQL into the clipboard and paste it with

    pbpaste > temp_infile && mysql -uroot -proot < temp_infile && rm temp_infile
    
    0 讨论(0)
提交回复
热议问题