简体   繁体   中英

Pass SQL statement from command line to Java code

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 eg 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

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.
        }
    }
}

如果要从终端执行命令,则该语句应传递到main方法的String [] args参数中的代码中,您应该可以在代码中引用该语句。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM