Ignite Query Exception - ignite

Im getting the following error:
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SELECT
""standard_item_cache"".""STANDARDITEM""._KEY,
""standard_item_cache"".""STANDARDITEM""._VAL FROM
""standard_item_cache"".""STANDARDITEM"" WHERE ITEMID[*] == ? "; SQL statement:
SELECT "standard_item_cache"."STANDARDITEM"._KEY,
"standard_item_cache"."STANDARDITEM"._VAL FROM
"standard_item_cache"."STANDARDITEM" WHERE itemId == ? [42000-196]
When I try to perform a simple query:
String itemId = params.get(Params.PARAM_ITEM_ID);
SqlQuery<String, StandardItem> sql = new SqlQuery<>(StandardItem.class, "itemid == ?");
try (QueryCursor<Cache.Entry<String, StandardItem>> cursor = standardItemIgniteCache.query(sql.setArgs(itemId))) {
logger.info("publish standard items from cache");
for (Cache.Entry<String, StandardItem> entry : cursor) {
logger.info("publish standard item: " + entry.getValue().toString());
}
logger.info("publishing standard items from cache done");
cursor.close();
}
Where is the mistake? Im doint it exactly like it is described in the apache ignite examples: https://apacheignite.readme.io/v1.0/docs/cache-queries

The mistake is in this tiny string: itemid == ?.
You used == instead of =. SQL equality operator is a single =.

Related

How to set large string as param without getting ORA-01460: unimplemented or unreasonable conversion error?

In spring-boot using namedParameterJdbcTemplate (Oracle db version 12 and odbc8 driver 12.2)
I am getting the following error while executing a SELECT query bound with a parameter larger than 4000 character whereas update queries working fine.
ORA-01460: unimplemented or unreasonable conversion requested
The unit test I am trying to execute;
#Test
public void testSqlSelectQueryLargeStringParameter() {
MapSqlParameterSource params = new MapSqlParameterSource();
params.addValue("param", theLargeStr);
// #formatter:off
String sql =
"SELECT NULL id, NULL text FROM DUAL WHERE 'X' != :param ";
// #formatter:on
namedParameterJdbcTemplate.queryForRowSet(sql, params);
}
Is there any way to set this large param via MapSqlParameterSource?
I am #ahmet-orhan 's colleague, we've found a solution.
Thanks #kfinity for your suggestion, It is working for insert and update but we are still getting this error when we set clob or blob as "paremeter" in select statements.
If using a driver that supports JDBC4.0, the right solution is create a DefaultLobHandler and set streamAsLob or createTemporaryLob to true.
MapSqlParameterSource params = new MapSqlParameterSource();
String myString = "";
for (int i = 0; i < MAX_CLOB_BLOB_SIZE_IN_SELECT; i++) {
myString = myString + "1";
}
DefaultLobHandler lobHandler = new DefaultLobHandler();
lobHandler.setStreamAsLob(true);
params.addValue("param", new SqlLobValue(myString, lobHandler), Types.CLOB);
// #formatter:off
String sql =
"SELECT 1 id FROM DUAL WHERE :param IS NOT NULL ";
// #formatter:on
Integer id = namedParameterJdbcTemplate.queryForObject(sql, params, Integer.class);
We prefer streamAsLob but to be honest we have no idea which one is better.
This comment points out that ORA-01460 in JDBC queries is the same as "ORA-01704: string literal too long". (You can't have string literals longer than 4000 characters.) Maybe try this solution?
params.addValue("param", theLargeStr, Types.CLOB);
Although also != won't work for clob comparison, so you'll also need to change your query to
SELECT NULL id, NULL text FROM DUAL WHERE dbms_lob.compare('X',:param) != 0

How to build SELECT * WHERE using collection of conditions

I want to build a SELECT statement using a list of conditions that come from the query string of a REST api. I wrote this function, but maybe it is vulnerable to SQL injection. Can someone tell me if this is vulnerable how to fix it? Perhaps I should use some kind of SQLBuilder package? or is there a way to do it with just dotNet. I'm using dotNet 4.6.1
string BuildSelect(NameValueCollection query)
{
var result = "SELECT * FROM MYTABLE";
if (query.Count == 0) return result;
var logic = " WHERE ";
foreach (string key in query)
foreach (string v in query.GetValues(key))
{
result += logic + key + " = " + v;
logic = " AND ";
}
return result;
}
Yes it is vulnerable to SQL injection attack. You could build your query to use parameters instead (you are simply using an = check only).
Since you know the tablename, that means you also know what the columns (keys) can be. Thus, you could loop your columns, if the collection has that key then add it to the where as a parameterized statement BUT value part is NOT passed as a string, you parse it to the type it should be (or let the backend do the conversion and get error if cannot be converted). In pseudocode:
List<string> clauses = new List<string>();
var result = "SELECT * FROM MYTABLE";
foreach( var col in myTable.Columns )
{
if (query.ContainsKey(col.Name))
{
clauses.Add( $"{col.Name} = #{col.Name}";
string v = query[col.Name];
command.Parameters.Add( $"#{col.Name}", col.Type).Value = typeParse(v);
}
}
if (clauses.Any())
{
result += " WHERE " + string.Join( " AND ", clauses );
}
return result;
HTH

Inserting data through GUI into sql server

I'm able to execute sql statements by writing the sql codes (Insert etc) on Eclipse and it is being displayed into sql server correctly. Connection has been done. But what should I do when a user wants to add data through a GUI interface (text field) and the data need to get stored into the database automatically ??
my code in the ADD button, but i'm getting the Error: java.lang.NullPointerException ! Help please..
try {
String pid = ProductID.getText();
String sql = "insert into Products_tbl values (' " +pid + " ')";
// Running the sql query
rs = st.executeQuery(sql);
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Welcome");
}
else if (count > 1) {
JOptionPane.showMessageDialog(null,"Duplicate User Access Denied");
}
else {
JOptionPane.showMessageDialog(null, " User Not Found ");
}
}
catch (Exception ex) {
System.out.println("Error: " + ex);
}
1- Using (' " +pid + " ')" is not safe because SQL injection may occur. Use SqlParameters instead. Please check:
https://www.w3schools.com/sql/sql_injection.asp
2- I am pretty sure something is wrong with the line: rs = st.executeQuery(sql);
Here, I bet the value of st is null. Make sure that your connection variable is defined and set correctly and you created the statement like below:
st = connection.createStatement();
You can also try executeupdate(query) instead of executequery(query) like:
int flag = st.executeUpdate(query);
Ref: https://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29
3- Please use printStackTrace() method while printing the error in the catch blog, the error message would be more understandable.
System.out.println("Error: " + ex.printStackTrace());

Sql Select If Statement not working but working as simple function without if statement

Need help, am trying to use Select if statement in Sql
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
When z.z_status='1' and z.z_id = '".$vid."'
else JError::raiseError(404, "Message");
";
Target Objective is: show list when z_status=1 and display J Error when z_status=0. However it's not working. This function works well
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = '".$vid."'
";
However when trying to modify using else statement it does not work.
Edit - Complete Function Code:-
$database =& JFactory::getDBO();
global $Itemid;
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = '".$vid."'
";
$database->setQuery($sql);
$rows = $database->loadObjectList();
return $rows[0];
You are confusing SQL and PHP and Joomla: The second query you wrote is the one you want to run. But the logic needs to be handled in php. Your sql engine doesn't know "else" (which is php) or JError (which is Joomla). Not to speak about the wrong use of " - as you wrote it's just a syntax error.
$db = JFactory::getDbo();
$sql = "Select *,
(select prod_name from #__mobile_products where prod_id=z.z_prod_id)
as cell_name from #__mobile_types AS z
Where z.z_status='1' and z.z_id = " . $db->quote($vid);
$db->setQuery($sql);
if ($result = $db->loadObject()) {
// the query returned something, you can use the result object
echo $result->prod_name;
} else {
if ($db->getErrorNum()) {
JError::raiseError(500, "Something went horribly wrong, the query returned the error ". $db->getErrorMsg());
} else {
echo "Your query returned no records i.e. no records satisfy the z_status=1 condition";
}
}
Finally, 404 is "not found", but it refers to the request, not the data in your application. You might want to return 500 if the query errors out, and 200 for all other requests. See here for more info on status codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

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);