0

Is it possible to run linux shell commands though jdbc in java code and how? I have been trying this:

Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager.getConnection("jdbc:mysql://" + this.host + "/" + this.db + "?", properties);
        statement = connect.createStatement();
        String sql = "\\! touch /home/dbsms/testfile";
        statement.execute(sql);

but I'm getting "You have an error in your SQL syntax;" error. The reason why I am trying this: MySQL server is running on a machine which is on a protected (no internet) network. My java application is designed to manipulate DB. It is a document management DB. So once a new document is inserted into DB I need to notify users. There is another machine on the same network which is able to send SMS. What I need to to is create a file that contains a text of an SMS and is named as a phone number, and the deamon on SMS machine will pick it up and process. I know that there are libs that would let me execute shell command on a remote computer via ssh, but I would like to use jdbc if possible.

2 Answers2

0

With jdbc, we are having a database connection, and this we must give a valid sql statement to execute. So you are getting above error.

But, with java you can execute shell commands. This article will help you.

Gimhani
  • 1,318
  • 13
  • 23
  • hmm yes that is true. However I need to create a file on a remote machine not a local one. But thank you anyway – Andrija Petrovic Aug 30 '18 at 08:58
  • then, ChannelSftp(https://epaul.github.io/jsch-documentation/simple.javadoc/com/jcraft/jsch/ChannelSftp.html) would help you. – Gimhani Aug 30 '18 at 09:02
  • @AndrijaPetrovic then, you can use JSch library(http://www.jcraft.com/jsch/). Or, as I've mentions use ssh command with Runtime.exec("ssh ....") and then use it to execute commands you need – Gimhani Aug 30 '18 at 09:13
0

Nope, JDBC is for executing SQL statements in a database.

Java can run OS level commands but they are limited to the box where the JVM is running.

It sounds to me (I can be wrong) that you want to run them in the server, not your local machine. If this is the case then you would need to open a remote connection to the server, probably using SSH or similar in order to run your command remotely.

The Impaler
  • 45,731
  • 9
  • 39
  • 76