Domanda

C'è un modo semplice per eseguire una query MySQL dalla riga di comando di Linux e l'uscita dei risultati di formato CSV ?

Ecco quello che sto facendo ora:

mysql -u uid -ppwd -D dbname << EOQ | sed -e 's/        /,/g' | tee list.csv
select id, concat("\"",name,"\"") as name
from students
EOQ

Si diventa disordinato quando ci sono un sacco di colonne che devono essere circondati da virgolette, o se ci sono citazioni nei risultati che devono essere sfuggito.

È stato utile?

Soluzione

Da http://www.tech-recipes.com/rx/1475/save-mysql-query-results-into-a-text-or-csv-file/

SELECT order_id,product_name,qty
FROM orders
WHERE foo = 'bar'
INTO OUTFILE '/var/lib/mysql-files/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

L'utilizzo di questo comando colonne non verranno esportati i nomi.

Si noti inoltre che /var/lib/mysql-files/orders.csv sarà sul MySQL server che è in esecuzione. L'utente che il processo di MySQL è in esecuzione deve disporre delle autorizzazioni per scrivere nella directory scelta, o il comando non riuscirà.

Se si desidera scrivere uscita sulla macchina locale da un server remoto (in particolare di un hosting o virtualizzare macchina come Heroku o Amazon RDS), questa soluzione non è adatta.

Altri suggerimenti

$ mysql your_database --password=foo < my_requests.sql > out.csv

Qual è scheda separata. Tubo in quel modo per ottenere un vero e proprio CSV (grazie @therefromhere):

... .sql | sed 's/\t/,/g' > out.csv
  

mysql --batch, -B

     

I risultati di stampa utilizzando la scheda come separatore di colonna, con ciascuna riga su una   nuova linea. Con questa opzione, mysql non utilizza il file di storia.   Risultati modalità batch in formato uscita non tabulare e fuoriuscita di   personaggi speciali. Escaping può essere disabilitato utilizzando la modalità raw; vedere   la descrizione per l'opzione --raw.

Questo vi darà un file separato da tabulazioni. Dal momento che le virgole (o stringhe contenenti virgola) non sono fuggiti, non è semplice per cambiare il delimitatore alla virgola.

Ecco un modo abbastanza gnarly di farlo. Trovato da qualche parte, non può prendere alcun credito

mysql --user=wibble --password wobble -B -e "select * from vehicle_categories;" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > vehicle_categories.csv

Funziona abbastanza bene. Ancora una volta, anche se una regex dimostra scrivere solo.


Regex Spiegazione:

  • s /// significa sostituire quello che c'è tra la prima // con ciò che è tra la seconda //
  • il "g" alla fine è un modificatore che significa "tutta esempio, non solo prima"
  • ^ (in questo contesto) significa all'inizio della riga
  • $ (in questo contesto) significa fine della riga

Quindi, mettendo tutto insieme:

s/'/\'/          replace ' with \'
s/\t/\",\"/g     replace all \t (tab) with ","
s/^/\"/          at the beginning of the line place a "
s/$/\"/          at the end of the line place a "
s/\n//g          replace all \n (newline) with nothing

Unix / Cygwin solo tubo attraverso 'tr':

mysql <database> -e "<query here>" | tr '\t' ',' > data.csv

NB .: Questo gestisce le virgole non embedded, né le schede embedded.

Questo mi ha salvato un paio di volte. Veloce e funziona!

  

--batch    risultati di stampa utilizzando come separatore colonna, con ciascuna riga su una   nuova linea.

     

--raw < em> disabilita carattere fuga (\ n, \ t, \ 0, e \)

Esempio:

mysql -udemo_user -p -h127.0.0.1 --port=3306 \
   --default-character-set=utf8mb4 --database=demo_database \
   --batch --raw < /tmp/demo_sql_query.sql > /tmp/demo_csv_export.tsv

Per completezza si potrebbe convertire in csv (ma fare attenzione perché le schede potrebbero essere all'interno i valori di campo - ad esempio campi di testo)

  

tr '\t' ',' < file.tsv > file.csv

La soluzione OUTFILE data da Paolo Tomblin provoca un file da scrivere sul server MySQL in sé, quindi questo funziona solo se si dispone di accedere al file , così come l'accesso di accesso o altri mezzi per recuperare il file da quella casella.

Se non si dispone di tale accesso, e l'output delimitato da tabulazioni è un sostituto ragionevole per CSV (per esempio, se il vostro obiettivo finale è quello di importare in Excel), quindi la soluzione di Serbaut (utilizzando mysql --batch e opzionalmente --raw ) è la strada da percorrere.

MySQL Workbench può esportare set di record in formato CSV, e sembra di gestire le virgole nei campi molto bene. Il CSV si apre in OpenOffice bene.

Come su:

mysql your_database -p < my_requests.sql | awk '{print $1","$2}' > out.csv

Tutte le soluzioni qui fino ad oggi, ad eccezione del banco di lavoro MySQL uno, non sono corrette e molto probabilmente non sicuri (ad esempio problemi di sicurezza) per almeno qualche possibile contenuti nel db mysql.

MySQL Workbench (e allo stesso modo phpMyAdmin) fornire una soluzione formalmente corretta, ma sono progettati per scaricare l'uscita della posizione di un utente. Non sono così utile per cose come l'automazione di esportazione dei dati.

Non è possibile generare in modo affidabile corretta csv dall'uscita del mysql -B -e 'SELECT ...' perché non si può codificare ritorni a capo e gli spazi bianchi nei campi. Il flag '-s' per mysql fa fare backslash fuga, e potrebbe portare a una soluzione corretta. Tuttavia, utilizzando un linguaggio di scripting (uno con strutture decenti interne di dati che è, non bash), e biblioteche dove i problemi di codifica sono già stati accuratamente elaborato è molto più sicuro.

Ho pensato di scrivere una sceneggiatura per questo, ma non appena ho pensato a quello che io chiamerei, mi venne in mente per la ricerca di lavoro pre-esistente con lo stesso nome. Mentre io non sono andato oltre a fondo, la soluzione a https://github.com/robmiller/mysql2csv sembra promettente. A seconda dell'applicazione, l'approccio yaml a specificare i comandi SQL potrebbe o non potrebbe fare appello però. Io non sono anche entusiasta con l'esigenza di una versione più recente di Ruby che viene fornito di serie con il mio Ubuntu 12.04 portatile o server Debian Squeeze. Sì, lo so che potrei usare RVM, ma preferisco non sostenere che per un semplice scopo tale.

Speriamo che qualcuno indicherà uno strumento adeguato, che ha avuto un po 'di test. In caso contrario, io probabilmente aggiornare questo quando trovo o scriverne uno.

Dalla linea di comando, si può fare questo:

mysql -h *hostname* -P *port number* --database=*database_name* -u *username* -p -e *your SQL query* | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > *output_file_name.csv*

Crediti: tabella Esportazione da Amazon RDS in un file CSV

Molte delle risposte in questa pagina sono deboli perché non gestiscono il caso generale di ciò che può accadere in formato CSV. per esempio. virgole e virgolette incorporati in campi e le altre condizioni che vengono sempre alla fine. Abbiamo bisogno di una soluzione generale che funziona per tutti i dati di input CSV validi.

Ecco una soluzione semplice e forte in Python:

#!/usr/bin/env python

import csv
import sys

tab_in = csv.reader(sys.stdin, dialect=csv.excel_tab)
comma_out = csv.writer(sys.stdout, dialect=csv.excel)

for row in tab_in:
    comma_out.writerow(row)

Nome quel file tab2csv, metterlo sul vostro percorso, dare i permessi di esecuzione, quindi utilizzarlo in questo modo:

mysql OTHER_OPTIONS --batch --execute='select * from whatever;' | tab2csv > outfile.csv

Le funzioni CSV di movimentazione Python coprono casi angolo di formato di input CSV (s).

Questo potrebbe essere migliorato per gestire file di grandi dimensioni tramite un approccio in streaming.

  1. logica:

CREATE TABLE () (SELECT data FROM other_table ) ENGINE=CSV ;

  

Quando si crea una tabella CSV, il server crea un file di formato tabella in   la directory del database. Il file inizia con il nome della tabella e ha un   estensione .frm. Il motore di archiviazione crea anche un file di dati. Il suo nome   inizia con il nome della tabella e ha un'estensione .CSV. Il file di dati è   un file di testo. Quando si memorizzano dati nella tabella, l'archiviazione   motore salva nel file di dati in formato valori separati da virgole.

Questo è semplice, e funziona su qualsiasi cosa senza bisogno di file in modalità di output o in batch:

select concat_ws(',',
    concat('"', replace(field1, '"', '""'), '"'),
    concat('"', replace(field2, '"', '""'), '"'),
    concat('"', replace(field3, '"', '""'), '"'))

from your_table where etc;

Spiegazione:

  1. Sostituire " con "" in ogni campo -> replace(field1, '"', '""')
  2. Surround ogni risultato tra virgolette -> concat('"', result1, '"')
  3. Inserisci una virgola tra ogni risultato citato -> concat_ws(',', quoted1, quoted2, ...)

Questo è tutto!

Questa risposta utilizza Python e una libreria di terze parti popolare, PyMySQL . Sto aggiungendo perché csv biblioteca è abbastanza potente per correttamente gestire molti sapori diversi di .csv e non altre risposte sono utilizzando il codice Python per interagire con il database.

import contextlib
import csv
import datetime
import os

# https://github.com/PyMySQL/PyMySQL
import pymysql

SQL_QUERY = """
SELECT * FROM my_table WHERE my_attribute = 'my_attribute';
"""

# embedding passwords in code gets nasty when you use version control
# the environment is not much better, but this is an example
# https://stackoverflow.com/questions/12461484
SQL_USER = os.environ['SQL_USER']
SQL_PASS = os.environ['SQL_PASS']

connection = pymysql.connect(host='localhost',
                             user=SQL_USER,
                             password=SQL_PASS,
                             db='dbname')

with contextlib.closing(connection):
    with connection.cursor() as cursor:
        cursor.execute(SQL_QUERY)
        # Hope you have enough memory :)
        results = cursor.fetchall()

output_file = 'my_query-{}.csv'.format(datetime.datetime.today().strftime('%Y-%m-%d'))
with open(output_file, 'w', newline='') as csvfile:
    # http://stackoverflow.com/a/17725590/2958070 about lineterminator
    csv_writer = csv.writer(csvfile, lineterminator='\n')
    csv_writer.writerows(results)

In alternativa alla risposta di cui sopra, si può avere una tabella di MySQL che utilizza il motore di CSV.

Quindi si avrà un file sul disco rigido che sarà sempre in formato CSV, che si può solo copiare senza elaborarlo.

Per espandere su risposte precedenti, il seguente one-liner esporta una singola tabella in un file separato da tabulazioni. E 'adatto per l'automazione, l'esportazione del database di tutti i giorni o giù di lì.

mysql -B -D mydatabase -e 'select * from mytable'

Per comodità, possiamo usare la stessa tecnica per elencare le tabelle di MySQL, e di descrivere i campi su una singola tabella:

mysql -B -D mydatabase -e 'show tables'

mysql -B -D mydatabase -e 'desc users'

Field   Type    Null    Key Default Extra
id  int(11) NO  PRI NULL    auto_increment
email   varchar(128)    NO  UNI NULL    
lastName    varchar(100)    YES     NULL    
title   varchar(128)    YES UNI NULL    
userName    varchar(128)    YES UNI NULL    
firstName   varchar(100)    YES     NULL    

Inoltre, se si sta eseguendo la query sulla riga di comando Bash, credo che il comando tr può essere utilizzato per sostituire le schede predefinite per delimitatori arbitrari.

$ echo "SELECT * FROM Table123" | mysql Database456 | tr "\t" ,

Sulla user7610, qui è il modo migliore per farlo. Con mysql outfile ci sono stati 60 minuti di proprietà dei file e modifica indesiderata.

Non è fredda, ma ha funzionato in 5 minuti.

php csvdump.php localhost root password database tablename > whatever-you-like.csv

<?php

$server = $argv[1];
$user = $argv[2];
$password = $argv[3];
$db = $argv[4];
$table = $argv[5];

mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

// fetch the data
$rows = mysql_query('SELECT * FROM ' . $table);
$rows || die(mysql_error());


// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings

$fields = [];
for($i = 0; $i < mysql_num_fields($rows); $i++) {
    $field_info = mysql_fetch_field($rows, $i);
    $fields[] = $field_info->name;
}
fputcsv($output, $fields);

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

?>

Ecco quello che faccio:

echo $QUERY | \
  mysql -B  $MYSQL_OPTS | \
  perl -F"\t" -lane 'print join ",", map {s/"/""/g; /^[\d.]+$/ ? $_ : qq("$_")} @F ' | \
  mail -s 'report' person@address

Lo script perl (uno Snipe da altrove) fa un bel lavoro di convertire i campi distanziati scheda in formato CSV.

Not exactly as a CSV format, but tee command from MySQL client can be used to save the output into a local file:

tee foobar.txt
SELECT foo FROM bar;

You can disable it using notee.

The problem with SELECT … INTO OUTFILE …; is that it requires permission to write files at the server.

Using the solution posted by Tim, I created this bash script to facilitate the process (root password is requested, but you can modify the script easily to ask for any other user):

#!/bin/bash

if [ "$1" == "" ];then
    echo "Usage: $0 DATABASE TABLE [MYSQL EXTRA COMMANDS]"
    exit
fi

DBNAME=$1
TABLE=$2
FNAME=$1.$2.csv
MCOMM=$3

echo "MySQL password:"
stty -echo
read PASS
stty echo

mysql -uroot -p$PASS $MCOMM $DBNAME -B -e "SELECT * FROM $TABLE;" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > $FNAME

It will create a file named: database.table.csv

If you have PHP set up on the server, you can use mysql2csv to export an (actually valid) CSV file for an abitrary mysql query. See my answer at MySQL - SELECT * INTO OUTFILE LOCAL ? for a little more context/info.

I tried to maintain the option names from mysql so it should be sufficient to provide the --file and --query options:

./mysql2csv --file="/tmp/result.csv" --query='SELECT 1 as foo, 2 as bar;' --user="username" --password="password"

"Install" mysql2csv via

wget https://gist.githubusercontent.com/paslandau/37bf787eab1b84fc7ae679d1823cf401/raw/29a48bb0a43f6750858e1ddec054d3552f3cbc45/mysql2csv -O mysql2csv -q && (sha256sum mysql2csv | cmp <(echo "b109535b29733bd596ecc8608e008732e617e97906f119c66dd7cf6ab2865a65  mysql2csv") || (echo "ERROR comparing hash, Found:" ;sha256sum mysql2csv) ) && chmod +x mysql2csv

(download content of the gist, check checksum and make it executable).

What worked for me:

SELECT *
FROM students
WHERE foo = 'bar'
LIMIT 0,1200000
INTO OUTFILE './students-1200000.csv'
FIELDS TERMINATED BY ',' ESCAPED BY '"'
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n';

None of the solutions on this thread worked for my particular case, I had pretty json data inside one of the columns, which would get messed up in my csv output. For those with a similar problem, try lines terminated by \r\n instead.

Also another problem for those trying to open the csv with Microsoft Excel, keep in mind there is a limit of 32,767 characters that a single cell can hold, above that it overflows to the rows below. To identify which records in a column have the issue, use the query below. You can then truncate those records or handle them as you'd like.

SELECT id,name,CHAR_LENGTH(json_student_description) AS 'character length'
FROM students
WHERE CHAR_LENGTH(json_student_description)>32767;

Tiny bash script for doing simple query to CSV dumps, inspired by https://stackoverflow.com/a/5395421/2841607.

#!/bin/bash

# $1 = query to execute
# $2 = outfile
# $3 = mysql database name
# $4 = mysql username

if [ -z "$1" ]; then
    echo "Query not given"
    exit 1
fi

if [ -z "$2" ]; then
    echo "Outfile not given"
    exit 1
fi

MYSQL_DB=""
MYSQL_USER="root"

if [ ! -z "$3" ]; then
    MYSQL_DB=$3
fi

if [ ! -z "$4" ]; then
    MYSQL_USER=$4
fi

if [ -z "$MYSQL_DB" ]; then
    echo "Database name not given"
    exit 1
fi

if [ -z "$MYSQL_USER" ]; then
    echo "Database user not given"
    exit 1
fi

mysql -u $MYSQL_USER -p -D $MYSQL_DB -B -s -e "$1" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > $2
echo "Written to $2"

Try this code:

SELECT 'Column1', 'Column2', 'Column3', 'Column4', 'Column5'
UNION ALL
SELECT column1, column2,
column3 , column4, column5 FROM demo
INTO OUTFILE '/tmp/demo.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';

For more information: http://dev.mysql.com/doc/refman/5.1/en/select-into.html

The following bash script works for me. It optionally also gets the schema for the requested tables.

#!/bin/bash
#
# export mysql data to CSV
#https://stackoverflow.com/questions/356578/how-to-output-mysql-query-results-in-csv-format
#

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# error
#
# show the given error message on stderr and exit
#
#   params:
#     1: l_msg - the error message to display
#
error() {
  local l_msg="$1"
  # use ansi red for error
  color_msg $red "Error:" 1>&2
  color_msg $red "\t$l_msg" 1>&2
  usage
}

#
# display usage 
#
usage() {
  echo "usage: $0 [-h|--help]" 1>&2
  echo "               -o  | --output      csvdirectory"    1>&2
  echo "               -d  | --database    database"   1>&2
  echo "               -t  | --tables      tables"     1>&2
  echo "               -p  | --password    password"   1>&2
  echo "               -u  | --user        user"       1>&2
  echo "               -hs | --host        host"       1>&2
  echo "               -gs | --get-schema"             1>&2
  echo "" 1>&2
  echo "     output: output csv directory to export mysql data into" 1>&2
  echo "" 1>&2
  echo "         user: mysql user" 1>&2
  echo "     password: mysql password" 1>&2
  echo "" 1>&2
  echo "     database: target database" 1>&2
  echo "       tables: tables to export" 1>&2
  echo "         host: host of target database" 1>&2
  echo "" 1>&2
  echo "  -h|--help: show help" 1>&2
  exit 1
}

#
# show help 
#
help() {
  echo "$0 Help" 1>&2
  echo "===========" 1>&2
  echo "$0 exports a csv file from a mysql database optionally limiting to a list of tables" 1>&2
  echo "   example: $0 --database=cms --user=scott --password=tiger  --tables=person --output person.csv" 1>&2
  echo "" 1>&2
  usage
}

domysql() {
  mysql --host $host -u$user --password=$password $database
}

getcolumns() {
  local l_table="$1"
  echo "describe $l_table" | domysql | cut -f1 | grep -v "Field" | grep -v "Warning" | paste -sd "," - 2>/dev/null
}

host="localhost"
mysqlfiles="/var/lib/mysql-files/"

# parse command line options
while true; do
  #echo "option $1"
  case "$1" in
    # options without arguments
    -h|--help) usage;;
    -d|--database)     database="$2" ; shift ;;
    -t|--tables)       tables="$2" ; shift ;;
    -o|--output)       csvoutput="$2" ; shift ;;
    -u|--user)         user="$2" ; shift ;;
    -hs|--host)        host="$2" ; shift ;;
    -p|--password)     password="$2" ; shift ;;
    -gs|--get-schema)  option="getschema";; 
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; usage;;
    (*) break;;
  esac
  shift
done

# checks
if [ "$csvoutput" == "" ]
then
  error "ouput csv directory not set"
fi
if [ "$database" == "" ]
then
  error "mysql database not set"
fi
if [ "$user" == "" ]
then
  error "mysql user not set"
fi
if [ "$password" == "" ]
then
  error "mysql password not set"
fi

color_msg $blue "exporting tables of database $database"
if [ "$tables" = "" ]
then
tables=$(echo "show tables" | domysql)
fi

case $option in
  getschema) 
   rm $csvoutput$database.schema
   for table in $tables
   do
     color_msg $blue "getting schema for $table"
     echo -n "$table:" >> $csvoutput$database.schema
     getcolumns $table >> $csvoutput$database.schema
   done  
   ;;
  *)
for table in $tables
do
  color_msg $blue "exporting table $table"
  cols=$(grep "$table:" $csvoutput$database.schema | cut -f2 -d:)
  if [  "$cols" = "" ]
  then
    cols=$(getcolumns $table)
  fi
  ssh $host rm $mysqlfiles/$table.csv
cat <<EOF | mysql --host $host -u$user --password=$password $database 
SELECT $cols FROM $table INTO OUTFILE '$mysqlfiles$table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
EOF
  scp $host:$mysqlfiles/$table.csv $csvoutput$table.csv.raw
  (echo "$cols"; cat $csvoutput$table.csv.raw) > $csvoutput$table.csv
  rm $csvoutput$table.csv.raw
done
  ;;
esac

If there is PHP installed on the machine you are using, you can write a PHP script to do that. It requires the PHP installation has the MySQL extension installed.

You can call the PHP interpreter from the command line like so:

php --php-ini path/to/php.ini your-script.php

I am including the --php-ini switch, because you may need to use your own PHP configuration that enables the MySQL extension. On PHP 5.3.0+ that extension is enabled by default, so that is no longer necessary to use the configuration to enable it.

Then you can write your export script like any normal PHP script:

<?php
    #mysql_connect("localhost", "username", "password") or die(mysql_error());
    mysql_select_db("mydb") or die(mysql_error());

    $result = mysql_query("SELECT * FROM table_with_the_data p WHERE p.type = $typeiwant");

    $result || die(mysql_error());

    while($row = mysql_fetch_row($result)) {
      $comma = false;
      foreach ($row as $item) {

        # Make it comma separated
        if ($comma) {
          echo ',';
        } else {
          $comma = true;
        }

        # Quote the quotes
        $quoted = str_replace("\"", "\"\"", $item);

        # Quote the string
        echo "\"$quoted\"";
      }
        echo "\n";
    }
?>

The advantage of this method is, that it has no problems with varchar and text fields, that have text containing newlines. Those fields are correctly quoted and those newlines in them will be interpreted by the CSV reader as a part of the text, not record separators. That is something that is hard to correct afterwards with sed or so.

The following produces tab-delimited and valid CSV output. Unlike most of the other answers, this technique correctly handles escaping of tabs, commas, quotes, and new lines without any stream filter like sed, awk, or tr. The example shows how to pipe a remote mysql table directly into a local sqlite database using streams. This works without FILE permission or SELECT INTO OUTFILE permission. I have added new lines for readability.

mysql -B -C --raw -u 'username' --password='password' --host='hostname' 'databasename'
-e 'SELECT
    CONCAT('\''"'\'',REPLACE(`id`,'\''"'\'', '\''""'\''),'\''"'\'') AS '\''id'\'',
    CONCAT('\''"'\'',REPLACE(`value`,'\''"'\'', '\''""'\''),'\''"'\'') AS '\''value'\''
    FROM sampledata'
2>/dev/null | sqlite3 -csv -separator $'\t' mydb.db '.import /dev/stdin mycsvtable'

The 2>/dev/null is needed to suppress the warning about the password on the command line.

If your data has NULLs, you can use the IFNULL() function in the query.

You can use below command from your SQL editor/Terminal:

"mysql -h(hostname/IP>) -u(username) -p(password) databasename <(query.sql) > outputFILE(.txt/.xls)"

e.g hostname -x.x.x.x

uname - username

password - password

DBName - employeeDB

queryFile - employee.sql

outputFile - outputFile.xls

mysql -hx.x.x.x -uusername -ppassword employeeDB< employee.sql> outputFile.xls

Make sure you are executing the command from the directory where SQL query is located or mention the full path of the sql query location in the above command.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top