Wie kann man das mysql Command in java laufen lassen?

fatfox

Bekanntes Mitglied
Hallo alle,

ich möchte von java aus das Command laufen lassen, aber das funktioniert irgendwie nicht, warum?

Java:
public static void main(String[] args) throws Exception{
    String cmd = "mysql --xml -uroot --password=xiaomimi netflix -e \"select * FROM MovieTitles\" > /home/conny/xml/gaga.xml";
    Runtime run = Runtime.getRuntime();
    Process pr = run.exec(cmd);
	}

Aber das Command kann direkt in Console laufen:
mysql --xml -uroot --password=xiaomimi netflix -e "select * FROM MovieTitles limit 0, 10" > /home/conny/Netflix/xml/AUTOMATIC/gaga.xml

Kann es sein, dass das Slash vor dem double quotation falsch ist?

Dank im Voraus!
 
Zuletzt bearbeitet:

fatfox

Bekanntes Mitglied
Funktioniert dein String in cmd so, wenn du es in der Shell angibst und ausführst?

Hi, ich weiß nicht was schell ist, aber der folgende Befehl funktioniert aufjeden fall in Console. In Java geht das nicht... :-/ (Ist Shell Linux Console?)


conny@panda:~$ mysql --xml -uroot --password=xiaomimi netflix -e "select * FROM MovieTitles" > /home/conny/xml/gaga.xml

Der Befehl bedeutet einfach, dass ich exportiere eine Tabelle als xml
 
Zuletzt bearbeitet:

DerEisteeTrinker

Bekanntes Mitglied
Gibt er in der Konsole noch iwelche Dinge aus, nachdem das Commando abgesetzt wurde?

Wenn ja, könntest du dem Process, den du da baust versuchen einen Stream zuzuweisen, dann siehst du was das Commando eventuell zurücklieferst
 

fatfox

Bekanntes Mitglied
Gibt er in der Konsole noch iwelche Dinge aus, nachdem das Commando abgesetzt wurde?

Wenn ja, könntest du dem Process, den du da baust versuchen einen Stream zuzuweisen, dann siehst du was das Commando eventuell zurücklieferst

Hi DerEisteeTrinker,

das Command läuft auf jeden fall in Console.

Aber in Java bekomme ich so was:

------------------------------------------------------------------------------------------------------------------------
Java:
mysql  Ver 14.14 Distrib 5.1.49, for debian-linux-gnu (i686) using readline 6.1
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license
Usage: mysql [OPTIONS] [database]
  -?, --help          Display this help and exit.
  -I, --help          Synonym for -?
  --auto-rehash       Enable automatic rehashing. One doesn't need to use
                      'rehash' to get table and field completion, but startup
                      and reconnecting may take a longer time. Disable with
                      --disable-auto-rehash.
  -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         Don't use history file. Disable interactive behavior.
                      (Enables --silent.)
  --character-sets-dir=name 
                      Directory for character set files.
  --column-type-info  Display column type information.
  -c, --comments      Preserve comments. Send comments to the server. The
                      default is --skip-comments (discard comments), enable
                      with --comments.
  -C, --compress      Use compression in server/client protocol.
  -#, --debug[=#]     This is a non-debug version. Catch this and exit.
  --debug-check       Check memory and open file usage at exit.
  -T, --debug-info    Print some debug info at exit.
  -D, --database=name Database to use.
  --default-character-set=name 
                      Set the default character set.
  --delimiter=name    Delimiter to be used.
  -e, --execute=name  Execute command and quit. (Disables --force and history
                      file.)
  -E, --vertical      Print the output of a query (rows) vertically.
  -f, --force         Continue even if we get an SQL error.
  -G, --named-commands 
                      Enable named commands. Named commands mean this program's
                      internal commands; see mysql> help . When enabled, the
                      named commands can be used from any line of the query,
                      otherwise only from the first line, before an enter.
                      Disable with --disable-named-commands. This option is
                      disabled by default.
  -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. WARNING: option deprecated; use
                      --disable-named-commands instead.
  -i, --ignore-spaces Ignore space after function names.
  --local-infile      Enable/disable LOAD DATA LOCAL INFILE.
  -b, --no-beep       Turn off beep on error.
  -h, --host=name     Connect to host.
  -H, --html          Produce HTML output.
  -X, --xml           Produce XML output.
  --line-numbers      Write line numbers for errors.
  -L, --skip-line-numbers 
                      Don't write line number for errors.
  -n, --unbuffered    Flush buffer after each query.
  --column-names      Write column names in results.
  -N, --skip-column-names 
                      Don't write column names in results.
  -O, --set-variable=name 
                      Change the value of a variable. Please note that this
                      option is deprecated; you can set variables directly with
                      --variable-name=value.
  --sigint-ignore     Ignore SIGINT (CTRL-C).
  -o, --one-database  Only update the default database. This is useful for
                      skipping updates to other database in the update log.
  --pager[=name]      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. Disable with --disable-pager. This
                      option is disabled by default.
  --no-pager          Disable pager and print to stdout. See interactive help
                      (\h) also. WARNING: option deprecated; use
                      --disable-pager instead.
  -p, --password[=name] 
                      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 or 0 for default to, in
                      order of preference, my.cnf, $MYSQL_TCP_PORT,
                      /etc/services, built-in default (3306).
  --prompt=name       Set the mysql prompt to this value.
  --protocol=name     The protocol to use for connection (tcp, socket, pipe,
                      memory).
  -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.
  --reconnect         Reconnect if the connection is lost. Disable with
                      --disable-reconnect. This option is enabled by default.
  -s, --silent        Be more silent. Print results with a tab as separator,
                      each row on new line.
  -S, --socket=name   The socket file to use for connection.
  --ssl               Enable SSL for connection (automatically enabled with
                      other flags).Disable with --skip-ssl.
  --ssl-ca=name       CA file in PEM format (check OpenSSL docs, implies
                      --ssl).
  --ssl-capath=name   CA directory (check OpenSSL docs, implies --ssl).
  --ssl-cert=name     X509 cert in PEM format (implies --ssl).
  --ssl-cipher=name   SSL cipher to use (implies --ssl).
  --ssl-key=name      X509 key in PEM format (implies --ssl).
  --ssl-verify-server-cert 
                      Verify server's "Common Name" in its cert against
                      hostname used when connecting. This option is disabled by
                      default.
  -t, --table         Output in table format.
  --tee=name          Append everything into outfile. See interactive help (\h)
                      also. Does not work in batch mode. Disable with
                      --disable-tee. This option is disabled by default.
  --no-tee            Disable outfile. See interactive help (\h) also. WARNING:
                      Option deprecated; use --disable-tee instead.
  -u, --user=name     User for login if not current user.
  -U, --safe-updates  Only allow UPDATE and DELETE that uses keys.
  -U, --i-am-a-dummy  Synonym for option --safe-updates, -U.
  -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.
  --connect_timeout=# Number of seconds before connection timeout.
  --max_allowed_packet=# 
                      The maximum packet length to send to or receive from
                      server.
  --net_buffer_length=# 
                      The buffer size for TCP/IP and socket communication.
  --select_limit=#    Automatic limit for SELECT when using --safe-updates.
  --max_join_size=#   Automatic limit for rows in a join when using
                      --safe-updates.
  --secure-auth       Refuse client connecting to server if it uses old
                      (pre-4.1.1) protocol.
  --server-arg=name   Send embedded server this as a parameter.
  --show-warnings     Show warnings after every statement.

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/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 option file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.

Variables (--variable-name=value)
and boolean options {FALSE|TRUE}  Value (after reading options)
--------------------------------- -----------------------------
auto-rehash                       TRUE
character-sets-dir                (No default value)
column-type-info                  FALSE
comments                          FALSE
compress                          FALSE
debug-check                       FALSE
debug-info                        FALSE
database                          (No default value)
default-character-set             latin1
delimiter                         ;
vertical                          FALSE
force                             FALSE
named-commands                    FALSE
ignore-spaces                     FALSE
local-infile                      FALSE
no-beep                           FALSE
host                              (No default value)
html                              FALSE
xml                               TRUE
line-numbers                      TRUE
unbuffered                        FALSE
column-names                      TRUE
sigint-ignore                     FALSE
port                              3306
prompt                            mysql> 
quick                             FALSE
raw                               FALSE
reconnect                         FALSE
socket                            /var/run/mysqld/mysqld.sock
ssl                               FALSE
ssl-ca                            (No default value)
ssl-capath                        (No default value)
ssl-cert                          (No default value)
ssl-cipher                        (No default value)
ssl-key                           (No default value)
ssl-verify-server-cert            FALSE
table                             FALSE
user                              root
safe-updates                      FALSE
i-am-a-dummy                      FALSE
connect_timeout                   0
max_allowed_packet                16777216
net_buffer_length                 16384
select_limit                      1000
max_join_size                     1000000
secure-auth                       FALSE
show-warnings                     FALSE
 
Zuletzt bearbeitet:

fatfox

Bekanntes Mitglied
Hi DerEisteeTrinker, könntest du vielleicht mir mal verraten, wie man sehen kann, welches command wurde von java tatsächlich ausgeführt?
 
G

Gast2

Gast
Du musst auf jedenfall den error- und outputstream des prozesses komplett auslesen, sonst kanns dein dass der Prozess blockt.
 

homer65

Top Contributor
Das Einfachste ist den kompletten MySQL Befehl in ein Shellskript auszulagern und von Java aus nur das Shellskript aufzurufen.
 

fatfox

Bekanntes Mitglied
Du musst auf jedenfall den error- und outputstream des prozesses komplett auslesen, sonst kanns dein dass der Prozess blockt.

Der Prozess gibt mir keine Error anzeige...

ich habe folgende Code hinzugefügt:
Java:
		// read the output
		
		BufferedReader stdInput = new BufferedReader(new
		InputStreamReader(pr.getInputStream()));
		BufferedReader stdError = new BufferedReader(new
		InputStreamReader(pr.getErrorStream()));
		System.out.println("Here is the standard output of the command:\n");
		String s = null;
		while ((s = stdInput.readLine()) != null) {
		System.out.println(s);
		}
		
		// read any errors from the attempted command
		 
		System.out.println("Here is the standard error of the command (if any):\n");
		while ((s = stdError.readLine()) != null) {
		System.out.println(s);
		}

dann bekomme ich dass Ergebnis wie von oben beschrieben.
 

fatfox

Bekanntes Mitglied
Das Einfachste ist den kompletten MySQL Befehl in ein Shellskript auszulagern und von Java aus nur das Shellskript aufzurufen.

Eh... homer65, könntest du für mich ein kleine Beispiel Code schreiben? Ich kenne java wirklich nicht so gut aus. :(

pr.exec("./shellskript.sh") ???? Das ist sehr praktisch. Ich probiere mal...
 
Zuletzt bearbeitet:

homer65

Top Contributor
Na, den Code hast du ja im Prinzip schon:
Code:
    String cmd = "/home/christian/my.sh";
    Runtime run = Runtime.getRuntime();
    Process pr = run.exec(cmd);
    pr.waitFor();
Auch der Einfachheit halber kannst du den absoluten Pfad zum shellskript angeben.
Anderfalls mußt du alles richtig machen damit dein Skript gefunden wird.
 

fatfox

Bekanntes Mitglied
Na, den Code hast du ja im Prinzip schon:
Code:
    String cmd = "/home/christian/my.sh";
    Runtime run = Runtime.getRuntime();
    Process pr = run.exec(cmd);
    pr.waitFor();
Auch der Einfachheit halber kannst du den absoluten Pfad zum shellskript angeben.
Anderfalls mußt du alles richtig machen damit dein Skript gefunden wird.

Hi Homer65,
ich weiß nicht, ob ich irgendwo falsh getippt habe, irgendwie funktioniert das gar nicht. Selbst wenn ich ein ganz einfach command in shellskript schreiben:
Java:
	    String cmd = "/home/conny/Netflix/xml/test/my.sh";
	    Runtime run = Runtime.getRuntime();
	    Process pr = run.exec(cmd);
	    pr.waitFor();

und mein shell skript ist ein ganz einfache Copy Command:

cp /home/conny/Netflix/xml/test/haha.txt /home/conny/Netflix/xml/test/hahacopy.txt

Ist der Verzeichnis falsch? soll man nicht mal "./" vor der String eingeben? Aber das funktioniert auch nicht.... :(
 

fatfox

Bekanntes Mitglied
Hi homer65,

Vielen Dank! jetzt funktioniert der shell Skript!!! :D

Aber wenn ich den Befehl ab und zu nach Situation ändern möchte, wird das nicht kompliziert?
 
Zuletzt bearbeitet:

homer65

Top Contributor
Schön das es funktioniert.
Wenn der abzusetzende Befehl veränderlich ist, dann sehe ich zwei Möglichkeiten:
(1) Du erstellt das Shellskript aus dem Java Programm bevor du es ausführst
(2) Du übergibst an das Shellskript eine Variable und wertest die im Skript aus
 

fatfox

Bekanntes Mitglied
Schön das es funktioniert.
Wenn der abzusetzende Befehl veränderlich ist, dann sehe ich zwei Möglichkeiten:
(1) Du erstellt das Shellskript aus dem Java Programm bevor du es ausführst
(2) Du übergibst an das Shellskript eine Variable und wertest die im Skript aus

Danke Homer! sehr nützlich und praktische Tip!!! :D
 
Ähnliche Java Themen
  Titel Forum Antworten Datum
Juelin Java und MySQL MariaDB - WHERE-Klausel Datenbankprogrammierung 17
W MySQL-Connector funktioniert nicht über WLAN -> MacOS Datenbankprogrammierung 10
Juelin MySQL Datenbankmit glassfish und Netbeans Datenbankprogrammierung 18
Auf MySql Datenbank zugreifen funktioniert nicht Datenbankprogrammierung 8
TheSkyRider MySQL Datenbankzuordnung in Verbindung mit Java Datenbankprogrammierung 7
Warum funktioniert MySQL nicht Datenbankprogrammierung 8
M MySQL Datenbank in Array Datenbankprogrammierung 2
P MySQL- Neues Passwort Datenbankprogrammierung 1
btwX28 mysql abfrage über phpmyadmin Datenbankprogrammierung 8
sserio SQL oder MySQL Datenbankprogrammierung 44
OnDemand Mysql Query Builder Datenbankprogrammierung 1
Z MySQL "Too many connections" auch nach schliessen der Connections. Datenbankprogrammierung 10
yakazuqi MySQL MySQL Connection reset Datenbankprogrammierung 7
OnDemand MySql Foreign Key nötig oder unnötig Datenbankprogrammierung 3
M Mysql Views und Hibernate Caching Datenbankprogrammierung 4
W MYSQL Datenbank Login Android Datenbankprogrammierung 3
OnDemand MySQL und mongoDB wann macht was Sinn? Datenbankprogrammierung 11
bueseb84 Spring Boot : Update Mysql Datenbank Datenbankprogrammierung 1
Avalon Attribute werden mit Unterstrich in eine MySQL Datenbank eingetragen Datenbankprogrammierung 10
D MYSQL goorm IDE - Wie speichern? Datenbankprogrammierung 0
OnDemand Mysql UPDATE if condition Datenbankprogrammierung 14
D MySQL Geburtsdatum per KW abfragen Datenbankprogrammierung 1
C Java MySQL check if value exists in database Datenbankprogrammierung 2
H Fehler bei getConnection zu MySQL Datenbank Datenbankprogrammierung 18
J MySQL - Primary Key Date,Time vs ID Datenbankprogrammierung 16
ruutaiokwu MySQL: Messwerte, welche stagnieren interpolieren? Datenbankprogrammierung 2
S Datenbank MySQL und Java Datenbankprogrammierung 8
Thallius MySQL JDBC auf Linux Server zu mySQL DB auf anderem Linux Server wirft Access denied Datenbankprogrammierung 5
P Adressadministration mit Java und mySQL Datenbankprogrammierung 14
D MySQL Abfrage Datenbankprogrammierung 5
D MySQL Abfrage sortieren Datenbankprogrammierung 4
platofan23 MySQL Java Programm findet Treiber für mySQL auf Debian-Server nicht? Datenbankprogrammierung 11
J MySQL MySQL Risiken bei Stromausfall minimieren Datenbankprogrammierung 9
D MySQL Abfrage SUM datediff Datenbankprogrammierung 3
H MySQL MySQL - Keine Verbindung zur Datenbank?! Datenbankprogrammierung 4
G MySQL Problem mit MySQL verbindung Datenbankprogrammierung 8
X MySQL Java hat keinen Zugriff auf MySQL Datenbankprogrammierung 9
Z [JDBC][MYSQL] Access denied Datenbankprogrammierung 7
D MySQL Connection richtig herstellen. Wie ? Datenbankprogrammierung 7
D Multiple Connection mit MySQL Datenbankprogrammierung 4
D MySQL Eibinden des "mysql-connector" in eine fertige Jar Datenbankprogrammierung 3
L MySQL Android zu externer MySQL Datenbank verbinden Datenbankprogrammierung 5
P Daten in eine mySQL Datenbank einfügen Datenbankprogrammierung 4
D MySQL Zeilen kumulieren Datenbankprogrammierung 8
D MySQL Abfrage mit kumulierten Werten Datenbankprogrammierung 16
K Servlet-MySQL DB Datenbankprogrammierung 2
X MySQL Json String in MySQL einfügen. Datenbankprogrammierung 20
OnDemand Update auf Mysql läuft nicht durch Datenbankprogrammierung 30
K Java Object mit Hibernate in MySQL abspeichern Datenbankprogrammierung 1
D Datumsformat aus MySQL ändern Datenbankprogrammierung 15
G MySQL Java Problem: Nullpointer Exception obwohl Daten vorhanden sind? Datenbankprogrammierung 2
K MySQL LAN-MySQL Server mit XAMPP Datenbankprogrammierung 2
R ERModel der Datebanken (ORACLE,MySQL,MS-SQL usw) Datenbankprogrammierung 4
X MySQL In MySQL Funktionen erstellen, wenn Zelle leer dann andere Zelle ändern? Datenbankprogrammierung 9
K Anfängerfrage CSV in MySQL Datenbankprogrammierung 41
I MySQL Wert nachträglich bearbeiten Datenbankprogrammierung 1
N MySQL Datenbank lokal Datenbankprogrammierung 3
B MySQL: Port ändern über GUI? Wo und wie Port ändern? Datenbankprogrammierung 0
B MySQL installieren - silent / User anlegen Datenbankprogrammierung 3
X MySQL Verbindungdsaufbau MySql auf Ubuntu-Server Datenbankprogrammierung 10
F MySQL Wie kann ich in Java Datensätze aus einer MySQL Datenbank gezielt in einzelne Arrays schreiben? Datenbankprogrammierung 9
P MySQL JPA / MySQL - Fehler bei type=innoDB Datenbankprogrammierung 8
M MySQL MySQL DATETIME-Import Datenbankprogrammierung 9
P MySQL Connection Global Datenbankprogrammierung 13
J mySQL- Java Application - Zugriff über Internet Datenbankprogrammierung 3
P MySQL-Verbindung in anderer Klasse nutzen Datenbankprogrammierung 2
D JavaFX Anwendung zugriff auf MySQL DB. Datenbankprogrammierung 2
D MySQL Grundsätzliche Fragen zu MySQL Datenbankprogrammierung 3
B MySQL LogIn Daten im Code verstecken Datenbankprogrammierung 3
M MySQL-Syntax-Fehler Datenbankprogrammierung 1
M In MySql Datenbank schreiben Datenbankprogrammierung 6
D mySQL Timestamp in RegularTimePeriod bzw Second Datenbankprogrammierung 3
H SHOW Tables in Java/MySQL Datenbankprogrammierung 8
windl MySQL und HSQLDB Datenbankprogrammierung 4
S Anbindung zur mysql von mit Swing und AWT Datenbankprogrammierung 22
F MySQL+ Netbeans: Datenbanken mit Automatisch generierten Entity Classes get und set Datenbankprogrammierung 2
I MySQL Hibernate / MySQL alias in WHERE clause Datenbankprogrammierung 1
C MYSQL kann wert nicht eintragen Datenbankprogrammierung 3
D Aktualisierung einer ListView mit Daten aus MySQL-DB Datenbankprogrammierung 5
F BPlaced MySql Datenbank ansprechen Datenbankprogrammierung 5
S MySQL MySQL will einfach nicht, bitte um Rat Datenbankprogrammierung 4
M MySQL Datenbank durchsuchen Datenbankprogrammierung 5
Z MySQL mysql Facharbeit: Tipps und Ideen gesucht Datenbankprogrammierung 5
dat_vin JavaFX Datenbankverbindung über JPA und MySQL Error Datenbankprogrammierung 0
K MySQL Datenbank 2facher Zugriff Datenbankprogrammierung 1
Z MySQL Shopsystem mit mysql und Java Datenbankprogrammierung 8
S [MySQL] Topliste Datenbankprogrammierung 2
H Datenbank-Anbindung Java/MySQL Datenbankprogrammierung 2
T MySQL MySQL - Insert into fügt zwei identische Datensätze ein Datenbankprogrammierung 2
A Eine MySQL Zeile mit JDBC löschen Datenbankprogrammierung 5
J Dateien in MySQL speichern & indizieren Datenbankprogrammierung 2
B MySQL MySQL-Abfrage von aufsummierter Zeit Datenbankprogrammierung 3
K MySQL Datenbankbackups Datenbankprogrammierung 5
P MySQL INSERT / UPDATE MySQL - perStoredProcedure oder direkt im Code Datenbankprogrammierung 3
kaoZ HyperSQL vs. MYSQL Datenbankprogrammierung 4
L JSONArray/JSONObject MySQL-Servlet Abfrage Datenbankprogrammierung 2
V Internationalization mit MySql Datenbankprogrammierung 1
K Adressverwaltung mit MySql und Java? Datenbankprogrammierung 11
M Java Mysql verbinden Datenbankprogrammierung 3
L Zugriff auf lokal gespeicherte mySQL Datenbank Datenbankprogrammierung 3

Ähnliche Java Themen

Neue Themen


Oben