-1

I am writing a code in which I am creating a JDBC connection and executing a select statement. I want to run the as a jar and give input to the where condition from the command line for e.g. java -jar abc.jar "abc". How can this be done?

try {
    strExecuteQuery = "select b.FIUSB_REQUEST_MESSAGE,b.FIUSB_RESPONSE_MESSAGE,a.fiusb_tran_id,a.FIUSB_SRV_REQ_TYPE"
        + " from fimaster.fiusb_transaction_tablehist a ,fimaster.FIUSB_TRANDETAILS_TABLE_HIST b"

        + " where a.fiusb_tran_id = b.fiusb_tran_id and a.FIUSB_SRV_REQ_TYPE in('XferTrnRev','XferTrnAdd','PmtAdd') and a.fe_req_ref_num='args1'";


    //PreparedStatement stmt=con.prepareStatement(strExecuteQuery);

    //strExecuteQuery.getClass();

    ddlStatement.execute(strExecuteQuery);
    ddlStatement.closeConnection();

I want to take args1 in the above code as the input in the command line

Vikas
  • 25
  • 6
  • 1
    Possible duplicate of [How do I parse command line arguments in Java?](https://stackoverflow.com/questions/367706/how-do-i-parse-command-line-arguments-in-java) – HamishD Jul 22 '19 at 12:24

2 Answers2

1

The simple (and insecure!) way is something like this:

// package declaration
// imports 
public class Main {
    public static void main(String[] args) {
        if (args.length >= 1) {
            String query = "select FOO from BLAH a where a.BAZ = '" 
                + args[0] + "'";
            Connection connection = ...
            Statement statement = connection.createStatement();
            ResultSet rs = statement.execute(query);
            // etcetera
        } else {
            // report missing command line argument.
        }
    }
}

The problem is that assembling an SQL query by string concatenation is vulnerable to SQL injection. Especially when some of the "parameters" may come from a non-trustworthy source.

So a better (more secure) way to do it is to use a PreparedStatement, and its syntactically safe parameter substitution mechanism:

// package declaration
// imports 
public class Main {
    public static void main(String[] args) {
        if (args.length >= 1) {
            String query = "select FOO from BLAH a where a.BAZ = ?";
            Connection connection = ...
            PreparedStatement statement = connection.createPreparedStatement(query);
            statement.setString(1, args[0]);
            ResultSet rs = statement.execute();
            // etcetera
        } else {
            // report missing command line argument.
        }
    }
}
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

If you are executing the command from the terminal, then the statement should be passed into the code in the String[] args parameter of the main method, from which you should be able to reference it in the code.