jdbcTemplate.query works fine when passing few parameters and doesn't work for others - sql

I have a select Oracle SQL that I am hitting using jdbcTemplate.query method. This returns a bean of the values from the table. I am passing a dynamic value to the query that will be used in the WHERE clause. However, the SQL values for few values that i am passing. But when I pass the value as NA it won't work. Any suggestions on this or help me with what am i missing?
private static final String regionSearchSql = "SELECT PRFLID, PRFLNM, RGN_CD FROM %PREFIX%MER_PRFL WHERE RGN_CD = ?";
public List<SearchProfileBean> regionSearchProfile(SearchProfileRequest searchProfileRequest) throws DatabaseQueryException {
try {
return jdbcTemplate.query((QueryUtility.getQueryWithPrefix(regionSearchSql,prefix)), new SearchProfileRowMapper(), searchProfileRequest.getRegionName());
} catch (Exception e) {
throw new DatabaseQueryException(QueryUtility.getQueryWithPrefix(regionSearchSql, prefix), e);
}
}
If i pass 'EMEA', 'LAC', 'JAPA' in searchProfileRequest.getRegionName() - the SQL returns perfect results. But if I pass 'NA' in searchProfileRequest.getRegionName(), it gives empty results. But there are rows in the table for NA.

Related

is it possible to get the execute sql that contains parameter when debugging mybatis source

I am setting a breakpoint in mybatis source BaseExecutor's queryFromDatabase function in Intellij Idea, this code block look like this:
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
but the boundSql content shows sql like this:
select * from article where channel_id in (?)
is it possible to get the execute sql in the trace? because the channel_id has more than 100 and the sql also contains other filter condition.

SQLite Error in statement insert with question mark

Hello I am writing a query to insert values in DB SQLite.
Firstly, I read from my records and searched for two values, for example, then I created a new table and inserted new values in.
My code snippet follows:
try
{
Class.forName("org.sqlite.JDBC");
Connection con=DriverManager.getConnection("jdbc:sqlite:tests.db");
con.setAutoCommit(false);
Statement st=con.createStatement();
st.executeUpdate("delete msearch");
ResultSet res=st.executeQuery("select * from newmobile_details");
Boolean rec=res.next();
if(!rec)
{
JOptionPane.showMessageDialog(null,"لايوجد سجلات");
}
else
{
do
{
String mid=res.getString(1);
String model=res.getString(2);
String name=res.getString(3);
int price=res.getInt(4);
String pcolor=res.getString(5);
String imei=res.getString(6);
java.sql.Date date=res.getDate(7);
String access=res.getString(8);
if(mname.equalsIgnoreCase(name))
{
PreparedStatement prp=con.prepareStatement("insert into msearch values(?,?,?,?,?,?,?,?)");
prp.setString(1,mid);
prp.setString(2,model);
prp.setString(3,name);
prp.setInt(4,price);
prp.setString(5,pcolor);
prp.setString(6,imei);
prp.setDate(7,date);
prp.setString(8,access);
prp.executeUpdate();
System.out.println("iam inside2");
rows++;
b=1;
jTextField2.setText("");
}
}while(res.next());
if(b==0)
{
JOptionPane.showMessageDialog(null,"لم يتم العثور على الموبايل ");
jTextField2.setText("");
}
}
con.commit();
con.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"The error is1:" +e);
}
I get only exception as below:
The error is1 :sql error or missing database in msearch syntax error
Larry makes a good point and looking at your code more carefully I believe the problem is with the statement
st.executeUpdate("delete msearch");
It seems to be saying you should be qualifying msearch with a database name.
This is the syntax for an insert statement
INSERT INTO TABLE_NAME (c1, c2, c3,...cN)
VALUES (v1, v2, v3,...vN);
You give a list of column names and a list of values.
You don't have the list of column names.
This can't work.

Apache DBUtils - Why need resultsethandler for Insert?

I run an insert statement using Apache DBUtils. However, I am not sure why I have to include ResultSetHandler for this case:
String theQuery = QueryGenerator.insertintoStats();
ResultSetHandler<Object> dummyHandler = new ResultSetHandler<Object>() {
#Override
public Object handle(ResultSet rs) throws SQLException
{
return null;
}
};
try
{
queryRunner.insert(connection, theQuery, dummyHandler, Constants.UUIDSTR.toString(), name, prevbackupTime,
curbackupTime, updStartTime, delStartTime, bkupType.toString(), rowCount);
}
catch (SQLException e)
{
LOGGER.info(theQuery.toString());
LOGGER.error("Caught exception!", e);
}
Similar's the case for insertbatch which does use ResultSetHandler. I have resorted to use batch call for batch queries. Can anyone explain why we would be needing resultset handler for insert?
From documentation https://commons.apache.org/proper/commons-dbutils/apidocs/:
public <T> T insert(String sql,
ResultSetHandler<T> rsh,
Object... params)
throws SQLException
rsh - The handler used to create the result object from the ResultSet
of auto-generated keys.
If you insert values in a table which generate id upon insertion, you can retrieve it back, for example see this answer how to do this manually : https://stackoverflow.com/a/1915197/947111
You need ResultSetHandler<T> rsh to iterate over ResultSet which returned with id's which has been created.

HQL :Hibernate update query

i use struts2 and hibernate jpa for my app and i have an error when traying using update query with hibernate
here is my code :
in my class dao
#Override
public void UpdateNoteEvaluation() {
try {
String hql="update Evaluation e " +
"SET e.Eval_NoteGlobal =: ( SELECT SUM( sv.SousEval_Note ) AS sum FROM sousevaluation sv )" +
"ORDER BY EVAL_ID DESC LIMIT 1 ";
Query q= session.createQuery(hql);
q.executeUpdate();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
in my class Action :
public String saveOrUpdate(){
sousevaldao.UpdateNoteEvaluation();
System.out.println("update note ok ok");
return SUCCESS;
}
so here i can't make the update i get this error :
java.lang.IllegalArgumentException: node to traverse cannot be null!
at org.hibernate.hql.ast.util.NodeTraverser.traverseDepthFirst(NodeTraverser.java:55)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:277)
knowing i have test the update query im phpmyadmin it's work fine
If query has been tested to be working one via phpMyAdmin, it is quite clear that query is SQL query - not a HQL query. Also syntax of query seems to contain MySQL SQL dialect specific LIMIT clause.
Query for native SQL queries can be created via Session.createSQLQuery(String queryString) method:
String sql = ...
Query q = session.createSQLQuery(sql);

JDBC select query returns wrong values

I was performing JDBC select query in my web service to return some values from my database. Part of this table is attached to this question. After performing following query:
SELECT * FROM uses WHERE uses_user_fk='22';
I receive only one row, but in database are two values that meet the query conditions, as you can see in attached picture. Can anyone tell me where I made a mistake. I’m using following JDBC instruction to execute the query
ResultSet tempResultSet = statement.executeQuery(query);
Bellow image of database table uses:
Below the compete method that query the database, argument query is the same as listed earlier “SELECT * FROM uses…”. I should add that the answer for that query is 4, I also try this query without using quotes (uses_user_fk=22) but the result was the same:
protected ArrayList<Integer> queryForIds(String query, String column) throws Exception {
ArrayList<Integer> ids = new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager
.getConnection(GeneralDatabaseConstants.DATABASE_CONNECTION_URL);
statement = connect.createStatement();
ResultSet tempResultSet = statement.executeQuery(query);
if (tempResultSet.next())
ids.add(new Integer(tempResultSet.getInt(column)));
} catch (Exception e) {
throw e;
} finally {
close();
}
return ids;
}
replace
if (tempResultSet.next())
with
while (tempResultSet.next())