How insert parameter from java code into SQL query with regex? - java

When I build query I use parameters like:
WAR_REPORT_CALLING_NUMBER = " and cal.calling_number = ? ";
and from code I insert parametr instead ? But now I need insert parameter into this string:
WAR_REPORT_MSG1 = " AND regexp_like(pe.answer_recived,'^[^0-9]*[?][^0-9]*$') ";
and this structure nor work. How do it?

You can assign the regular expression to the parameter and change the condition with :
regexp_like(pe.answer_recived,?) ";

Related

Preparing a query as String using JdbcTemplate

I have the following query and params. I dont want to execute the query(jdbcTemplate.queryForObject) but instead pass this query with params as string to another method. How can I assign this params to prepared statement and save the query as a string?
final String QUERY = "select * "
+ "from gfc.LSI_ELGBLTY "
+ "where INSURANCE_ID = ? and "
+ "SYS_CD = ? and "
+ "ACCT_TYPE in (?)";
Object[] params = new Object[] {
request.getInsuranceId(),
request.getSystemId(),
AcctNameBuilder.toString()
};
You don't want to do this because replacing ? in a prepared statements with actual values in most cases will force database to re-process and re-plan the SQL query. It's really wasteful, if you already have a prepared statement so use it.
You could however define a shared PreparedStatementCreator object and pass it to JdbcTemplate#query(PreparedStatementCreator psc, ResultSetExtractor<T> rse).
Take a look at String.format.
String.format("Hello %s, %d", "world", 50);
Would return "Hello world 50".
Format specifiers:
%s - insert a string
%d - insert a signed integer (decimal)
%f - insert a real number as standard notation
An other example:
String.format("The {0} is repeated again: {0}", "word");
Return: "The word is repeated again: word"

Passing Oracle functions as String in Java

I have a query like this..
String query = "UPDATE tbl_customer_policies SET "+
"start_date = ?," +
"next_pay_date = ?,"+
"maturity_date = ?, " +
"modified_at = CURRENT_TIMESTAMP,"+
"modifier = ?, status = ? " +
"WHERE id = ?";
Now in place of the place-holder for start_date I want to pass a string like SYSDATE.
What I am doing now is setting that string in a variable called String startDate = "SYSDATE" and binding it to that place-holder. But I guess it does not seem to work. I get this exception
ORA-01858: a non-numeric character was found where a numeric was expected
I have to pass Oracle functions like that. How to achieve that?
If it will always be sysdate you don't need to parameterize it.
Set it directly in the query like this:
String query = "UPDATE tbl_customer_policies SET "+
"start_date = sysdate," + // or "start_date = ADD_MONTHS(SYSDATE, 12),"
"next_pay_date = ?,"+
"maturity_date = ?, " +
"modified_at = CURRENT_TIMESTAMP,"+
"modifier = ?, status = ? " +
"WHERE id = ?";
And set all the others parameters like you did before.
Use function TO_DATE (docs)
for example
"UPDATE tbl_customer_policies SET "+
"start_date = TO_DATE(?, 'DD-MON-RR')," +
"next_pay_date = TO_DATE(?, 'DD-MON-RR'),"+
and don't forget pass parameters in format like '27-OCT-98' in this case.
P.S.
I misunderstood the question so try to correct my answer.
The described problem is for limitations of PreparedStatement Java class.
PreparedStatement object is used for storing a reference to some precompiled (and optimized) SQL statement.
So you have to supply only values of parameters for filling them.
Functions must be evaluated before using their results and they aren't able to be placed there.
I guess you can use a workaround with Oracle Structured Types.
You can pass them as reference types with PreparedStatement's setRef() method.
Using functions can be implemented with a wrapper in constructor of object.
I didn't try it but it seems to me it is a possible solution.

Use PreparedStatement to build a query

I was wondering if using PreparedStatement.setString() was a good idea (possible, sensible?) to dynamically build a query.
For example :
sql code:
SELECT * FROM table1 WHERE table1.category = ? ?
java code:
ps.setString(1,"category1");
ps.setString(2,"AND table1.category = 'category2'");
Also, would it be possible to do something like:
ps.setString(1,"category1");
ps.setString(2," AND table1.category = ?");
ps.setString(3,"category2");
Best regards
Unfortunately, NO.
PreparedStatements are strictly for values only. Table Names and Column Names (as well as conditions in your example) are not allowed. So the best way to do is to concatenate it with the string.
String others = " AND table1.category = ?";
String query = "SELECT * FROM table1 WHERE table1.category = ? " + others;
java code:
ps.setString(1,"category1");
ps.setString(2,"category2");
Whatever you put inside setString will go within single quotes ' ' and will not be interpreted as a query.

keep column name variable in Java INSERT INTO command with PreparedStatement?

I have the following problem:
I have two tables in one data base which consist of the same columns besides the name of the last column. I want to write data into them using Java.
I want to use the same preparedStatement for both tables, where I check with an if-command whether it is table1 or table2. table2 has amount10 as the name for the last column, table1 has amount20 for it. This number is stored in a variable within my code.
Below you can see a (simplified) example and how I tried to let the column name variable but it doesn't work. Is there any way to fix this without copying the whole statement and manually changing the number variable?
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount`+"number") VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount`+"number" = ? ; ";
PreparedStatement insertDataStmt;
This will not work since variables number and table are not going to be magically injected into your insertData string while you are changing them.
I'd to a method prepareInsertstatement(String table, String number) that would return correct PreparedStatement:
public void prepareInsertStatement(Connection conn, Strint table, String number) {
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount+"number"') VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount+"number"' = ? ; ";
PreparedStatement insertDataStmt = conn.prepareStatement(insertData);
return insertDataStmt;
}
Just remember to close the PreparesStatement when you don't need it any more.
I suppose that reason for that is invalid syntax. When you concatenate string for last column name you use code 'amount' + number. If your number value is 20, than concat result will be
'amount'20 that cause invalid syntax exception. Just move one extra ' after number.
"'amount" + number + "'"
Note: log, or just error that appears during this statement execution would be very useful to find right answer for your question.

Escaping a single quote when using JdbcTemplate

We're using JdbcTemplate to modify our underlying Oracle database. We're doing this by way of the update(String sql) method.
The code looks somehow like the following:
String name = "My name's yellow";
String sql = "update FIELD set NAME = '" + name "' where ID = 10
jdbcTemplate.update(sql);
This causes the error:
java.sql.SQLException: ORA-00933: SQL command not properly ended
The problem is the unescaped ' in the name variable.
What's the most convenient and correct way to escape this character?
Use PreparedStatement. That way you nominate a placeholder and the JDBC driver will perform this correctly by sending the database the statement, plus the parameters as arguments.
String updateStatement =
"update " + dbName + ".COFFEES " +
"set TOTAL = TOTAL + ? " +
"where COF_NAME = ?";
PreparedStatement updateTotal = con.prepareStatement(updateStatement);
updateTotal.setInt(1, e.getValue().intValue());
updateTotal.setString(2, e.getKey());
The question marks in the above represent the placeholders.
Because these values get passed as parameters, you don't have problems with quoting, and it protects you against SQL injection too.
Try for name :
if ( name.contains("'") ){
name.replaceAll("'", "''");
}

Categories

Resources