IntelliJ IDEA not recognizing SQL dialect - java

We use IntelliJ IDEA actively and we have our wrappers for work with DB (PostgreSQL). The thing is that when we use placeholders, SQL is stopped being highlighted.
"select * from " + schema + ".users where id = " + id + ";";
This code is not recognised as SQL, so highlighting doesn't work.

I agree with Jesper, you should try using preparedStatements, not only would your Statements get more secure, also the problem which you are currently having should be solved by it.

Related

Sonarqube warned sql injection on the input-driven column name in my hibernate sql

My java (Hibernate, MySql) code takes the input data to decide which column I want to update as below:
String hsql = "update People set " + inputColumnName + " = null";
Query query = myHibernateSession.createQuery(hsql);
query.executeUpdate();
However, Sonarqube said "Change this code to not construct SQL queries directly from user-controlled data". Anyway I can avoid this error (either fix this or by-pass sonarqube check without turn this rule off)?
You need to restrict the variable to be a column name and remove potential for insertion of a statement. Using bind variables would help but take a look at some examples such as these: https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html

Why does this SQL-Statement lead to an error?

I am getting quite angry with this, so I seek help from the crowd ;)
What I want to do: We have a Unity learning game which shall implement a login window. The entered credentials are then hashed (the pw is) and sent to the server, who then should check this against a database.
I have the following table:
xy.users_confirms with the following colums:
id username email password hashcode created
Why does my code
String sql = "SELECT " + "xy.users_confirms.password as pwhash, "
+"FROM xy.users_confirms " +"WHERE xy.users_confirms.username = " +"\"userNameToGetHashFor\"";
lead me to the SQLException "Parameter index out of range (1 > number of parameters, which is 0)"
?
Thanks, any input is much appreciated!
Try this:
String parameter = "'"+ strNameToGetHashFor + "'";
String sql = "SELECT " + "xy.users_confirms.password as pwhash, "
+"FROM xy.users_confirms "
+"WHERE xy.users_confirms.username ="+ parameter;
You are using varchar value as a parameter so it's need to be quot like this.'username'. or you can use Stored Procedure.
Personally, I would try getting a working query using the custom query box directly in phpmyadmin. Once you have a working query you can re-write it in java.
And I would try writing the syntax like this into the phpmyadmin query box:
SELECT password as pwhash
FROM xy.users_confirms
WHERE username ='userNameToGetHashFor'
Using the above syntax I don't see anyway your error could persist.
Phpmyadmin screen cap showing custom query box: http://screencast.com/t/9h8anH0Aj
(the 2 empty text boxes in screen cap are just me hiding my database info)
The comma after pwhash is one potential cause:
+ "xy.users_confirms.password as pwhash*!*,*!* "
Depending on the DBMS, you may also need to use single quotes instead of double quotes like this:
+ "'userNameToGetHashFor'";
Also this code is potentially vulnerable to a SQL Injection attack so you may want to make the userNameToGetHashFor a parameter rather than concatenating the string into the SQL statement.

Derby SQL Syntax error: Encountered "." when copying from one database to another

I'm using Derby DB and trying to copy data from a table in one database to a table with the same table definition in another database.
What is the correct syntax to specify the database.scheme.table in Derby SQL?
I've tried using the following select statement
statement = "INSERT INTO CH003..MHALL..CH_COMPANY SELECT * FROM CH001..MHALL..CH_COMPANY WHERE COMPANY_NUMBER = '" + companyNumber + "'";
but get the error Caused by: java.sql.SQLException: Syntax error: Encountered "." at line 1, column 22.
Changing the code to
statement = "INSERT INTO CH003.MHALL.CH_COMPANY SELECT * FROM CH001.MHALL.CH_COMPANY WHERE COMPANY_NUMBER = '" + companyNumber + "'";
I get the error SQLSyntaxErrorException: Syntax error: Encountered "." at line 1, column 27.
Is it possible to do this in Derby? Do you know the correct syntax?
Thank you for your help.
A single Derby JDBC connection is connected to exactly one Derby database, so this is not possible in the way that you have attempted it.
However, there are other methods that you could use.
For example, you could use SYSCS_UTIL.SYSCS_EXPORT_TABLE to export the data from the table into a CSV file, then you could open a connection to the target database and use the SYSCS_UTIL.SYSCS_IMPORT_DATA to import that data. See https://db.apache.org/derby/docs/10.11/ref/rrefexportproc.html and http://db.apache.org/derby/docs/10.11/ref/rrefimportdataproc.html.
Or, you could read that data into, say, a data structure in your Java program, like an ArrayList, and then open a connection to your target database and write it out.
Or, you could use a tool like Apache DdlUtils to copy the data from one table to another: http://db.apache.org/derby/integrate/db_ddlutils.html
I'm sure there are other possibilities, but since you didn't give a lot of background about the underlying goal you're trying to accomplish, I won't try to speculate about why one approach might be better or worse than another.

Java Update Sql statement error

I am trying to update a Db2 database using Java and the following code:
String sSqlString = "UPDATE P6DEVCDB00.P6OSTAPF SET STATVAL = '" + sStatVal + "' WHERE OPIID = '" + sOperationsitemid + "' AND CONGRPC = '" + sConfigGrpCode + "'";
// Do your select on a Db table.
//statement = con.createStatement();
statement = con.prepareStatement(sSqlString);
int RowsAffected = statement.executeUpdate();
con.commit();
System.out.println(RowsAffected);
I then get the following error :
DB2 SQL Error: SQLCODE=-7008, SQLSTATE=55019, SQLERRMC=P6OSTAPF ;
P6DEVCDB00;3, DRIVER=3.58.81
I have printed out the sql that it's going to run :
UPDATE P6DEVCDB00.P6OSTAPF SET STATVAL = 'ON'
WHERE OPIID = 'B20120707000681531' AND CONGRPC = 'STKLSTSTAT
When I run this sql directly with a SQLUI tool it works and the record gets updated...
Your problem is that you're attempting to use transactions over tables that are not 'journaled' - that is, setup for transactions.
Ideally, you should set up all tables (that will be run under a transaction) as journaled, specifically to test that property; regardless of being able to simulate failures, you need to make sure that your code can handle being under transactions.
Also, depending on your situation, you may not need to explicitly manage transactions. If you're using a framework like Spring, they can usually manage transactions for you, although this will usually mean that you still need journaling on your iSeries tables.
If you're just trying to test basic code behavior, look into using an in-memory database, such as HSQLDB (can emulate some LUW DB2 behavior, but not library lists, unfortunately) - this will absolve you of the need to have a connection to your box, and to set up journaling.

I need help with this error: java.lang.NoSuchMethodError

I have this Java code (JPA):
String queryString = "SELECT b , sum(v.votedPoints) as votedPoint " +
" FROM Bookmarks b " +
" LEFT OUTER JOIN Votes v " +
" on (v.organizationId = b.organizationId) " +
"WHERE b.userId = 101 " +
"GROUP BY b.organizationId " +
"ORDER BY votedPoint ascending ";
EntityManager em = getEntityManager();
Query query = em.createQuery(queryString);
query.setFirstResult(start);
query.setMaxResults(numRecords);
List results = query.getResultList();
I don't know what is wrong with my query because it gives me this error:
java.lang.NoSuchMethodError: org.hibernate.hql.antlr.HqlBaseParser.recover(Lantlr/RecognitionException;Lantlr/collections/impl/BitSet;)V
at org.hibernate.hql.antlr.HqlBaseParser.fromJoin(HqlBaseParser.java:1802)
at org.hibernate.hql.antlr.HqlBaseParser.fromClause(HqlBaseParser.java:1420)
at org.hibernate.hql.antlr.HqlBaseParser.selectFrom(HqlBaseParser.java:1130)
at org.hibernate.hql.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:702)
at org.hibernate.hql.antlr.HqlBaseParser.selectStatement(HqlBaseParser.java:296)
at org.hibernate.hql.antlr.HqlBaseParser.statement(HqlBaseParser.java:159)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:271)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:134)
at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:94)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1650)
Thanks.
You definitely have an issue with the version of hibernate and ANTLR jars that you are using. The recover method wasn't present in the ANTLR Parser class until version 2.7.6? If you are using an earlier version of ANTLR, such as 2.7.2, then you will see this problem.
Using maven can cause this sort of situation, where you depend on Hibernate and its transitive dependencies, but something 'closer'; e.g. Struts; providers a different, earlier version of ANTLR and that earlier version gets resolved in your application.
If you can provide the version of jars involved, we would be able to help some more. Once you have fixed the issue with the jar versions, you should get a more revealing error message which shows what is wrong with your HQL expression.
Stab in the dark - Are you sure you have a consistent set of jars - perhaps you need to get the antlr jar that comes with the hibernate distribution you are using...
I've found the problem:
because this is a native query, java classes for this 2 tables must have some special attributes:
in Bookmarks.java class
#OneToMany(mappedBy = "bookmarkId")
private Collection votesCollection;
and in Votes.java class
#JoinColumn(name = "bookmark_id", referencedColumnName = "bookmark_id")
#ManyToOne
[private Bookmarks bookmarkId;
and i have also changed the query to work
tring queryString = "SELECT b, sum(v.votedPoints) " +
"FROM Bookmarks b " +
"LEFT OUTER JOIN b.votesCollection v " +
"WHERE b.userId = 101 " +
"GROUP BY b.organizationId " +
"ORDER BY sum(v.votedPoints) asc ";
thanks for the help
May be you have some double-quotes " missing or which should be doubled in your HQL.
Illustration here.
Or you miss some simple quotes as illustrated there
The query seems to be invalid unless it's an artifact of formatting.
I think you meant this:
Select b, ...
to be:
Select b.organizationId, ...
??
I have the consistent set of jars because simple queries like this one
"SELECT b FROM table_name b WHERE b.userId = 102 "
are working. I have verified all double quotes and everything is alright.
My database is: mysql, and I use jpa to connect to it. I don't know what is causing the problem. Maybe this type of join, i don't know
Er, isnt your query trying to select b which is a table alias and thats not allowed as far as I know.
I'd probably guess that something is going wrong with your query, because the method HqlBaseParser fails to lookup is called recover(RecognitionException, Bitset). Perhaps this query fails for some reason the other simpler queries don't (and the NoSuchMethod exception is thrown when attempting to recover from that error).
java.lang.NoSuchMethodError: org.hibernate.hql.antlr.HqlBaseParser.recover(Lantlr/RecognitionException;Lantlr/collections/impl/BitSet;)V
Your query is still wrong. Maybe it works with your driver/db but it isn't standard SQL. You should be selecting b.* or b.organizationId.

Categories