[bash] mysql query

Pagina: 1
Acties:
  • 218 views sinds 30-01-2008
  • Reageer

  • |orion
  • Registratie: Juli 2002
  • Laatst online: 16-04 15:16
Ik ben momenteel bezig met iets waarmee je via een php script (webinterface) in een databeest een bepaalde URL plaatst waarna het gedownload gaat worden door middel van een bash script (als dat niet handig is sta ik open voor suggesties), ik moet nog uitzoeken hoe ik een bash script ga aanroepen vanuit php maar dat is van latere zorg.

Ik heb dus een bash script gemaakt dat die query uitvoert maar als ik em start krijg ik de mysql help pagina. Ik heb de query al in een variabele moeten zetten omdat ie anders al helemaal niet uitgevoerd werd.

dit is m'n script:
code:
1
2
3
4
5
6
7
#!/bin/bash

QUERY="\"SELECT * FROM \`list\` WHERE \`index\`=1;\"";
echo $QUERY

RESULT=`mysql -u download -p linuxdebian --exec=$QUERY download`;
echo $RESULT


en dit is het resultaat:
sebastiaan@linuxbak:~/scripts$ ./testje
"SELECT download testje FROM `list` WHERE `index`=1;"
mysql Ver 11.16 Distrib 3.23.49, for pc-linux-gnu (i686) Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB This software comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to modify and redistribute it under the GPL license Usage: mysql [OPTIONS] [database] -?, --help Display this help and exit. -A, --no-auto-rehash No automatic rehashing. One has to use 'rehash' to get table and field completion. This gives a quicker start of mysql and disables rehashing on reconnect. -B, --batch Print results with a tab as separator, each row on a new line. Doesn't use history file. --character-sets-dir=... Directory where character sets are located. -C, --compress Use compression in server/client protocol. -D, --database=.. Database to use. --default-character-set=... Set the default character set. -e, --execute=... Execute command and quit. (Output like with --batch) -E, --vertical Print the output of a query (rows) vertically. -f, --force Continue even if we get an sql error. -g, --no-named-commands Named commands are disabled. Use \* form only, or use named commands only in the beginning of a line ending with a semicolon (;) Since version 10.9 the client now starts with this option ENABLED by default! Disable with '-G'. Long format commands still work from the first line. -G, --enable-named-commands Named commands are enabled. Opposite to -g. -i, --ignore-space Ignore space after function names. -h, --host=... Connect to host. -H, --html Produce HTML output. -L, --skip-line-numbers Don't write line number for errors. --no-pager Disable pager and print to stdout. See interactive help (\h) also. --no-tee Disable outfile. See interactive help (\h) also. -n, --unbuffered Flush buffer after each query. -N, --skip-column-names Don't write column names in results. -O, --set-variable var=option Give a variable an value. --help lists variables. -o, --one-database Only update the default database. This is useful for skipping updates to other database in the update log. --pager[=...] Pager to use to display results. If you don't supply an option the default pager is taken from your ENV variable PAGER (). Valid pagers are less, more, cat [> filename], etc. See interactive help (\h) also. This option does not work in batch mode. -p[password], --password[=...] Password to use when connecting to server If password is not given it's asked from the tty. -P, --port=... Port number to use for connection. -q, --quick Don't cache result, print it row by row. This may slow down the server if the output is suspended. Doesn't use history file. -r, --raw Write fields without conversion. Used with --batch -s, --silent Be more silent. -S --socket=... Socket file to use for connection. -t, --table Output in table format. -T, --debug-info Print some debug info at exit. --tee=... Append everything into outfile. See interactive help (\h) also. Does not work in batch mode. -u, --user=# User for login if not current user. -U, --safe-updates[=#], --i-am-a-dummy[=#] Only allow UPDATE and DELETE that uses keys. -v, --verbose Write more. (-v -v -v gives the table output format) -V, --version Output version information and exit. -w, --wait Wait and retry if connection is down. Default options are read from the following files in the given order: /etc/mysql/my.cnf /var/lib/mysql/my.cnf ~/.my.cnf The following groups are read: mysql client The following options may be given as the first argument: --print-defaults Print the program argument list and exit --no-defaults Don't read default options from any options file --defaults-file=# Only read default options from the given file # --defaults-extra-file=# Read this file after the global files are read Possible variables for option --set-variable (-O) are: connect_timeout current value: 0 max_allowed_packet current value: 16777216 net_buffer_length current value: 16384 select_limit current value: 1000 max_join_size current value: 1000000
en dat leek toch verdacht veel op de output van 'mysql --help'. Nu is mijn vraag dus: wat doe ik verkeerd en hoe doe ik het goed? ik ben er al achter gekomen dat bash niet echt happig was op de backquotes (vandaar dat ik er maar escape characters van heb gemaakt). Mischien doe ik het wel op de meest ONefficiente manier (kan best voor iemand van mijn niveau ;), maar leg me dan ff uit hoe het wel moet aub. Dan leer ik dr meteen ook nog iets van :)

alvast bedankt!

  • Wilke
  • Registratie: December 2000
  • Laatst online: 16:34
Je moet sowieso nog een database opgeven. Bij mij werkt dit:

code:
1
mysql -B -u <mijnusername> -p <mijnpassword> -D <welkedatabase> -e "<eenquery>"


Die -B zorgt ervoor dat je de uitvoer in Batch-formaat krijgt, dat betekent dat je de velden gescheiden door tabs krijgt (in plaats van de 'mooie', maar lastiger door een machine te parsen uitvoer).

Als je de uitvoer wilt gaan parsen, probeer dan eens te vogelen met het commando 'cut':

code:
1
mysql -B -u wilke -p <mijnpass> -D forum -e "SELECT * FROM Users WHERE id<10" | cut -f3

Dit geeft je het derde veld van elke regel (zie ook 'man cut'), in mijn geval is dat een lijstje met nicknames van mensen met een database-ID<10.

Succes ermee :)

  • |orion
  • Registratie: Juli 2002
  • Laatst online: 16-04 15:16
Wilke schreef op 28 augustus 2002 @ 10:08:
Je moet sowieso nog een database opgeven. Bij mij werkt dit:

code:
1
mysql -B -u <mijnusername> -p <mijnpassword> -D <welkedatabase> -e "<eenquery>"


Die -B zorgt ervoor dat je de uitvoer in Batch-formaat krijgt, dat betekent dat je de velden gescheiden door tabs krijgt (in plaats van de 'mooie', maar lastiger door een machine te parsen uitvoer).

Als je de uitvoer wilt gaan parsen, probeer dan eens te vogelen met het commando 'cut':

code:
1
mysql -B -u wilke -p <mijnpass> -D forum -e "SELECT * FROM Users WHERE id<10" | cut -f3

Dit geeft je het derde veld van elke regel (zie ook 'man cut'), in mijn geval is dat een lijstje met nicknames van mensen met een database-ID<10.

Succes ermee :)
't werkte meteen nadat ik '-p' verving door '--password=' 8) bedankt!

  • |orion
  • Registratie: Juli 2002
  • Laatst online: 16-04 15:16
oke, het werkt WEL in bash zelf, maar niet als ik het in een script zet :(
deze regel word uitgevoerd door het script:
code:
1
mysql -B -u download --password=linuxdebian -D download -e "SELECT download testje FROM `list` WHERE `index`=1;"


en dit is nu de scriptcode:
code:
1
2
3
4
5
6
7
8
9
#!/bin/bash

QUERY="\"SELECT * FROM \`list\` WHERE \`index\`=1;\"";
echo $QUERY

echo mysql -B -u download --password=linuxdebian -D download -e $QUERY

RESULT=`mysql -B -u download --password=linuxdebian -D download -e $QUERY`;
echo $RESULT


en nog steeds krijg ik dezelfde 'error' (is het wel een error?)

  • majornono
  • Registratie: Juni 2002
  • Laatst online: 04-04 23:16
code:
1
echo mysql -B -u download --password=linuxdebian -D download -e $QUERY


Ik zou deze regel veranderen in:
code:
1
mysql -B -u download --password=linuxdebian -D download -e $QUERY

dus zonder de echo

Problem Exists Between Chair And Keyboard


  • Super_ik
  • Registratie: Maart 2001
  • Laatst online: 17:44

Super_ik

haklust!

-p<wachtwoord> kan ook ipv --password=
zolang je t passwoord maar tegen de -p aanzet, dus zonder spatie

8<------------------------------------------------------------------------------------
Als ik zo door ga haal ik m'n dood niet. | ik hou van goeie muziek


  • |orion
  • Registratie: Juli 2002
  • Laatst online: 16-04 15:16
majornono schreef op 28 augustus 2002 @ 12:16:
code:
1
echo mysql -B -u download --password=linuxdebian -D download -e $QUERY


Ik zou deze regel veranderen in:
code:
1
mysql -B -u download --password=linuxdebian -D download -e $QUERY

dus zonder de echo
als ik alle regels wegcomentariseer en alleen de jouwe neem, en dan het script start dan kwakt ie meteen de mysql help pagina op mn scherm :/ tussen de output staat onderstaande regel, hetgeen ik wel interressant vind aangezien ik geen -O heb gebruikt:

code:
1
2
3
4
5
6
Possible variables for option --set-variable (-O) are:
connect_timeout       current value: 0
max_allowed_packet    current value: 16777216
net_buffer_length     current value: 16384
select_limit          current value: 1000
max_join_size         current value: 1000000

  • MyDyingBride
  • Registratie: November 2001
  • Laatst online: 19-04 20:18
Tabel en kolomnamen mogen niet tussen quotjes te staan.

  • |orion
  • Registratie: Juli 2002
  • Laatst online: 16-04 15:16
MyDyingBride schreef op 28 augustus 2002 @ 13:50:
Tabel en kolomnamen mogen niet tussen quotjes te staan.
Dit is nu mijn code (in de file 'testje'), en als ik dan './testje' doe dan krijg ik weer die mysql help pagina :?

code:
1
2
3
4
#!/bin/bash

QUERY="\"SELECT * FROM list WHERE index=1;\"";
mysql -B -u download --password=linuxdebian -D download -e $QUERY


mischien zie ik iets over het hoofd, daarom maar de output van het script hieronder:
code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
sebastiaan@linuxbak:~/scripts$ ./testje
mysql  Ver 11.16 Distrib 3.23.49, for pc-linux-gnu (i686)
Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL license

Usage: mysql [OPTIONS] [database]

  -?, --help            Display this help and exit.
  -A, --no-auto-rehash  No automatic rehashing. One has to use 'rehash' to
                        get table and field completion. This gives a quicker
                        start of mysql and disables rehashing on reconnect.
  -B, --batch           Print results with a tab as separator, each row on
                        a new line. Doesn't use history file.
  --character-sets-dir=...
                        Directory where character sets are located.
  -C, --compress        Use compression in server/client protocol.
  -D, --database=..     Database to use.
  --default-character-set=...
                        Set the default character set.
  -e, --execute=...     Execute command and quit. (Output like with --batch)
  -E, --vertical        Print the output of a query (rows) vertically.
  -f, --force           Continue even if we get an sql error.
  -g, --no-named-commands
                        Named commands are disabled. Use \* form only, or
                        use named commands only in the beginning of a line
                        ending with a semicolon (;) Since version 10.9 the
                        client now starts with this option ENABLED by
                        default! Disable with '-G'. Long format commands
                        still work from the first line.
  -G, --enable-named-commands
                        Named commands are enabled. Opposite to -g.
  -i, --ignore-space    Ignore space after function names.
  -h, --host=...        Connect to host.
  -H, --html            Produce HTML output.
  -L, --skip-line-numbers
                        Don't write line number for errors.
  --no-pager            Disable pager and print to stdout. See interactive
                        help (\h) also.
  --no-tee              Disable outfile. See interactive help (\h) also.
  -n, --unbuffered      Flush buffer after each query.
  -N, --skip-column-names
                        Don't write column names in results.
  -O, --set-variable var=option
                        Give a variable an value. --help lists variables.
  -o, --one-database    Only update the default database. This is useful
                        for skipping updates to other database in the update
                        log.
  --pager[=...]         Pager to use to display results. If you don't supply
                        an option the default pager is taken from your ENV
                        variable PAGER ().
                        Valid pagers are less, more, cat [> filename], etc.
                        See interactive help (\h) also. This option does
                        not work in batch mode.
  -p[password], --password[=...]
                        Password to use when connecting to server
                        If password is not given it's asked from the tty.

  -P, --port=...        Port number to use for connection.
  -q, --quick           Don't cache result, print it row by row. This may
                        slow down the server if the output is suspended.
                        Doesn't use history file.
  -r, --raw             Write fields without conversion. Used with --batch
  -s, --silent          Be more silent.
  -S  --socket=...      Socket file to use for connection.
  -t, --table           Output in table format.
  -T, --debug-info      Print some debug info at exit.
  --tee=...             Append everything into outfile. See interactive help
                        (\h) also. Does not work in batch mode.
  -u, --user=#          User for login if not current user.
  -U, --safe-updates[=#], --i-am-a-dummy[=#]
                        Only allow UPDATE and DELETE that uses keys.
  -v, --verbose         Write more. (-v -v -v gives the table output format)
  -V, --version         Output version information and exit.
  -w, --wait            Wait and retry if connection is down.

Default options are read from the following files in the given order:
/etc/mysql/my.cnf /var/lib/mysql/my.cnf ~/.my.cnf
The following groups are read: mysql client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit
--no-defaults           Don't read default options from any options file
--defaults-file=#       Only read default options from the given file #
--defaults-extra-file=# Read this file after the global files are read

Possible variables for option --set-variable (-O) are:
connect_timeout       current value: 0
max_allowed_packet    current value: 16777216
net_buffer_length     current value: 16384
select_limit          current value: 1000
max_join_size         current value: 1000000

  • MyDyingBride
  • Registratie: November 2001
  • Laatst online: 19-04 20:18
code:
1
2
3
4
#!/bin/bash

QUERY="SELECT * FROM list WHERE index=1;"
mysql -B -u download --password=linuxdebian -D download -e "$QUERY"


Probeer het zo maar eens.

  • |orion
  • Registratie: Juli 2002
  • Laatst online: 16-04 15:16
MyDyingBride schreef op 28 augustus 2002 @ 14:17:
code:
1
2
3
4
#!/bin/bash

QUERY="SELECT * FROM list WHERE index=1;"
mysql -B -u download --password=linuxdebian -D download -e "$QUERY"


Probeer het zo maar eens.
code:
1
2
sebastiaan@linuxbak:~/scripts$ ./testje
ERROR 1064 at line 1: You have an error in your SQL syntax near 'index=1' at line 1


:'( dat was waarom die backquotes om dat index heen stonden, zonder kreeg ik niet voor elkaar

  • MyDyingBride
  • Registratie: November 2001
  • Laatst online: 19-04 20:18
|orion schreef op 28 augustus 2002 @ 14:21:
[...]


:'( dat was waarom die backquotes om dat index heen stonden, zonder kreeg ik niet voor elkaar
Ach natuurlijk, index is een gereserveerd woord :Z

Zoiets dan:

code:
1
2
3
4
#!/bin/bash

QUERY="SELECT * FROM list WHERE \`index\`=1;"
mysql -B -u download --password=linuxdebian -D download -e "$QUERY"

  • |orion
  • Registratie: Juli 2002
  • Laatst online: 16-04 15:16
MyDyingBride schreef op 28 augustus 2002 @ 14:44:
[...]


Ach natuurlijk, index is een gereserveerd woord :Z

Zoiets dan:

code:
1
2
3
4
#!/bin/bash

QUERY="SELECT * FROM list WHERE \`index\`=1;"
mysql -B -u download --password=linuxdebian -D download -e "$QUERY"
* |orion zn ogen puilen uit :|
ik zit nu al de hele dag te klooien en nu ineens werkt het! w00h00!
Pagina: 1