write results of sql query to a file in mysql

前端 未结 5 991
心在旅途
心在旅途 2021-02-01 01:44

I\'m trying to write the results of a query to a file using mysql. I\'ve seen some information on the outfile construct in a few places but it seems that this only writes the fi

5条回答
  •  悲&欢浪女
    2021-02-01 02:12

    If you are running mysql queries on the command line. Here I suppose you have the list of queries in a text file and you want the output in another text file. Then you can use this. [ test_2 is the database name ]

    COMMAND 1

    mysql -vv -u root -p test_2  < query.txt >  /root/results.txt 2>&1
    

    Where -vv is for the verbose output.

    If you use the above statement as

    COMMAND 2

    mysql -vv -u root -p test_2  < query.txt  2>&1 >  /root/results.txt
    

    It will redirect STDERR to normal location (i.e on the terminal) and STDOUT to the output file which in my case is results.txt

    The first command executes the query.txt until is faces an error and stops there.

    That's how the redirection works. You can try

    #ls key.pem asdf > /tmp/output_1 2>&1 /tmp/output_2
    

    Here key.pm file exists and asdf doesn't exists. So when you cat the files you get the following

    # cat /tmp/output_1
    key.pem
    #cat /tmp/output_2
    ls: cannot access asdf: No such file or directory
    

    But if you modify the previous statement with this

    ls key.pem asdf > /tmp/output_1 > /tmp/output_2 2>&1
    

    Then you get the both error and output in output_2

    cat /tmp/output_2
    
    ls: cannot access asdf: No such file or directory
    key.pem
    

提交回复
热议问题