javamysqllinuxjschremote-connection

How to execute an “insert into” query to a remote database with channel.connect();


This is the java code I have tried to insert into my remote database table.

session.connect();
Channel channel = session.openChannel("exec");

String query = "INSERT INTO table_name
(id,serialno,userid,checktime,checktype,eventType) 
VALUES(502,1011,0078,'2017-04-17 17:27:51',6,23)";

((ChannelExec) channel).setCommand("mysql -uuser -ppwd -h localhost -e'" + 
query + "' database_name");
    InputStream in = channel.getInputStream();
    channel.connect();

I used the same code to execute "select *" query, instead for "Insert query" it executed perfectly and I got the output. But in this case it doesn't. Please help me find a solution.


Solution

  • You Need to escape double quotes With \" , because double quotes are used as delimiters in Java.

    String query = "INSERT INTO table_name
    (id,serialno,userid,checktime,checktype,eventType) 
    VALUES(502,1011,0078,'2017-04-17 17:27:51',6,23)"                
    
    ((ChannelExec) channel).setCommand("mysql -uroot -proot -h localhost -e\"" + query + "\" yourdbname");