how to replace a string value in java - java

i replace a particular string in a statement like the following
SQL = SQL.replaceAll("CUSTOMER_NUMBER", customer);
this conversion goes as integer but i want to replace this as a string like the following
AND CIMtrek_accountlist_customer_number = '0002538'
but at present it replaces like the following
AND CIMtrek_accountlist_customer_number = 0002538
how to do this in java.

Just get it to output the ' as well as the customer variable
SQL = SQL.replaceAll("CUSTOMER_NUMBER", "'" + customer + "'");
However as #jlordo mentioned in a comment, you should look at using prepared statements which will allow you to inject values into a prepared sql statement.

Though you should be using PreparedStatement if you are running SQL, However if placeholder "CUSTOMER_NUMBER" is under your control, It is better to use String.format. See and example here

Related

JDBC prepared statement to query JSON using json_exists

I'm facing trouble transforming the below query to jdbc prepared statement and setting the parameters.
oracle query:
select * from TRANSACTION_DUMMY where ID = 'aa'
and JSON_EXISTS(TRANSACTION_DUMMY_INDEX FORMAT JSON,
'$.header.lineItems[*].status?(#=="complete")')
translated query:
select * from TRANSACTION_DUMMY where ID = ?
and JSON_EXISTS(TRANSACTION_DUMMY_INDEX FORMAT JSON,
'$.header.lineItems[*].status?(#==?)')
the issue is how to set parameters in the query.
tried playing around with indexes but always getting the error, invalid column index.
any pointers how to handle the above scenario using java jdbc prepared statement?
thanks
According to the documentation, the second argument to JSON_EXISTS is a special string literal called JSON_path_expression.
If the value of the expression should change dynamically, it will be easiest to create it on the client (Java) side and then concatenate it into the query. You cannot pass the path expression as a bind variable because Oracle expects it to be a literal, i.e. a "parse-time constant". As you noticed, you'll get an ORA-40454: path expression not a literal error message if you try to pass the expression as a bind value.
The following code uses Java's String.format() for injecting the expression into the SQL template:
String sql = "select * from TRANSACTION_DUMMY where ID = 'aa' "
+ "and JSON_EXISTS(TRANSACTION_DUMMY_INDEX_FORMAT_JSON, %s)";
// here you could have some code for modifying jsonPathExpression dynamically,
// e.g. changing the status based on some criteria
String jsonPathExpression = "'$.header.lineItems[*].status?(#==\"complete\")'";
try (Statement st = myConnection.createStatement(String.format(sql, jsonPathExpression))) {
ResultSet st = ps.executeQuery();
// Process result set
}

Lookup and extract db value based on input (Java & SQL Server)

New to java.
I am attempting to write a class that will input a username, run a query on the username to find the ID, and subsequently use that ID in "where clauses" on all my other classes.
This is the statement that I execute (which will only ever return a recordset of a single row):
String sqlStatement = "SELECT AccountHolderId, Passcode from CIS4720.DBO.AccountHolder " +
"where Username = '" + logonName + "'";
Here is my attempt at extracting the ID via the username...
while (rset.next())
{
if(rset.getInt("Username")==logonName){
int whosOnFirst = rset.getInt("AccountHolderId");
}
I saw another answer on the forum that says you can't assign database values to variables. If that is the case, what is a better strategy?
(Also, I realize I'm not parameterizing, but I'd like to get this working before fixing that issue. This is for a course assignment so I am not worried about hack attacks).
P. S. Thanks I fixed the double equals sign (and the extra parenthesis) in the code above.
Here are some comments about the code:
rset.getInt("Username") will get the column Username from the result but it also looks for an Integer column because of getInt. You are not selecting that column in the sql statement so will error out.
If you select it and get a string, use .equals() instead of == to compare string. Also, one = is assignment and == is comparison.
You can use getString to read Strings from the result set.
You don't need to check the username and match it since your query should return exactly that user's data so I would remove the if condition entirely and just have the getInt line there.

Appscan source edition - SQL Injection

I am using Appscan source edition for Java Secure Coding. It is reporting an SQL injection in my application. The issue is that we are generating the query dynamically in code so I cannot use a prepared statement. Instead I have to us e Esapi.encoder().encodeForSql(new OracleCodec(), query). AppScan does not consider this to mitigate the SQL injection issue.
final String s = "SELECT name FROM users WHERE id = " +
Esapi.encoder().encodeForSql(new OracleCodec(), userId);
statement = connection.prepareStatement(s);
This code additionally does not work for ESAPI.encoder()
How can I resolve this issue?
what you should do is
final String s = "SELECT name FROM users WHERE id = ?"
statement = connection.prepareStatement(s);
statement.setString(1, userId);
The documentation for encodeForSQL recommends a PreparedStatement which you can still use which dynamically generated queries:
Encode input for use in a SQL query, according to the selected codec
(appropriate codecs include the MySQLCodec and OracleCodec). This
method is not recommended. The use of the PreparedStatement interface
is the preferred approach. However, if for some reason this is
impossible, then this method is provided as a weaker alternative. The
best approach is to make sure any single-quotes are double-quoted.
Another possible approach is to use the {escape} syntax described in
the JDBC specification in section 1.5.6. However, this syntax does not
work with all drivers, and requires modification of all queries.
Let's check what the encoder is doing to see why your code have an injection vulnerability. The encoder calls encodeCharacter in the oracle codec which simply replaces single quotes with two single quotes:
public String encodeCharacter( char[] immune, Character c ) {
if ( c.charValue() == '\'' )
return "\'\'";
return ""+c;
}
This only makes sense if the value is inside single quotes, which string values would be. If id is actually an integer and you wanted to concatenate it with the query, then you would convert it to an int type first instead of using this encoder.

ExecuteUpdate with possible single quotes

I have the following code:
sql = update [myTable] set content = '" map.getString() + "' where id = " map.getKey();
stmt.executeUpdate(sql);
This is running in a loop, and map.getString() can return a string with single or double quotes in them. I've tried escaping it with multiple quotes around map.getString() (for example
sql = update [myTable] set content = ''" map.getString() + "'' where id = " map.getKey();
But with no luck.
How can I get it to update the content column with the literal value of map.getString()?
Sample error I receive is: (there are many similar ones)
java.sql.SQLException: Incorrect syntax near 's'.
or
java.sql.SQLException: Invalid SQL statement or JDBC escape, terminating ''' not found.
Avoid using concatenate strings of parameter values for building your request:
it is not safe (possible sql injection)
it is not optimized (as the db engine will have always to parse the request even if always the same string is sent to the db)
it will generated lot of bad conversion error (special character etc)
Prefer using PreparedStatement with bind parameters.
Example:
PreparedStatement stmt = connection.prepareStatement("UPDATE mytable SET content = ? WHERE id = ?");
stmt.setString(1, map.getString());
stmt.setInt(2,map.getKey());
stmt.executeUpdate();
Using bind parameters will avoid conversion mistakes and syntax error you are encountering
Use a PreparedStatement. See http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html . They are precomiled, and thus more amenable for executing in loops as well as handling content containing characters which otherwise require special handling.

Java sql char prepared statement

I have a problem with a prepared statements with a char(3) parameter.
When I put the string directly into the SQL string I have no problem and the result set is correct, here's an example:
WHERE REQ.SERVICEID = 'SIN'
However, when I try to use a prepared statement in a safer way, I obtain no data!
The code is below:
" WHERE REQ.SERVICEID = ? "
and then
statement.setString(1,"SIN");
What is the problem?
Make sure you are using utf-8, i.e. with mysql:
jdbc:mysql://localhost:3306/db_name?characterEncoding=UTF-8
For other databases, there should be analog options.

Categories

Resources