nested exception is java.sql.SQLException: Invalid column name ORACLE - java

I tried to execute the following oracle query using JdbcTemplate in Java:
select RESOURCE_ID
from REPRO_PRINTING_JOB
where (USER_ID=? and PRINTING_CENTER_ID=?)
group by RESOURCE_ID
union all
select RESOURCE_ID
from REPRO_PRINTING_JOB_OLD
where (USER_ID=? and PRINTING_CENTER_ID=? and STATE='CM')
group by RESOURCE_ID
The query is working perfectly in oracle query browser but its not working during the execution in java. What could be the source of this problem? I´ve heard something about Jdbc cannot handle case sensitive. Is this true?
ADDED JAVA CODE(CORRECTED) :
I call the query using getStatement() which retrieves the query from external source(a properties file) as belows :
public List<PrintingJob> getPrintingJobsByCreatedUserId(String createdUserId, String userId) {
if(log.isDebugEnabled()) {
log.debug("getReportItemsByUserId(" + createdUserId + "," + userId + ")");
}
try {
System.out.println("getPrintingJobsByResourceId : createdUserId :"+createdUserId+",userId : "+userId);
return getJdbcTemplate().query(getStatement("gen.report.userid"),
new Object[]{createdUserId, userId, createdUserId, userId},
new PrintingJobMapper());
} catch (DataAccessException ex) {
log.error("Error executing query: " + ex.getClass() + ":" + ex.getMessage());
return null;
}
}

The reason you are getting this error is because it is an error from the JDBC driver or java.sql API, not from the database. Note the lack of ORA-XXXXX in the exception message. If it contained that, then it would be related to syntax, invalid name or something that would go wrong on the database server side.
SQLExceptions are thrown in java for anything related to the SQL api, not just from errors that occur when statements are sent over the connection... In this case, it is likely that the query in fact ran correctly but the result set API is giving you errors (rs.getLong("blah"), where column "blah" doesn't exist in your select) is causing problems.

Related

Sqlite-JDBC update with LIMIT clause?

I am trying to use the update query with the LIMIT clause using sqlite-JDBC.
Let's say there are 100 bob's in the table but I only want to update one of the records.
Sample code:
String name1 = "bob";
String name2 = "alice";
String updateSql = "update mytable set user = :name1 " +
"where user is :name2 " +
"limit 1";
try (Connection con = sql2o.open()) {
con.createQuery(updateSql)
.addParameter("bob", name1)
.addParameter("alice", name2)
.executeUpdate();
} catch(Exception e) {
e.printStackTrace();
}
I get an error:
org.sql2o.Sql2oException: Error preparing statement - [SQLITE_ERROR] SQL error or missing database (near "limit": syntax error)
Using
sqlite-jdbc 3.31
sql2o 1.6 (easy database query library)
The flag:
SQLITE_ENABLE_UPDATE_DELETE_LIMIT
needs to be set to get the limit clause to work with the update query.
I know the SELECT method works with the LIMIT clause but I would need 2 queries to do this task; SELECT then UPDATE.
If there is no way to get LIMIT to work with UPDATE then I will just use the slightly more messy method of having a query and sub query to get things to work.
Maybe there is a way to get sqlite-JDBC to use an external sqlite engine outside of the integrated one, which has been compiled with the flag set.
Any help appreciated.
You can try this query instead:
UPDATE mytable SET user = :name1
WHERE ROWID = (SELECT MIN(ROWID)
FROM mytable
WHERE user = :name2);
ROWID is a special column available in all tables (unless you use WITHOUT ROWID)

java-How to perform SQL injection for testing purposes?

I have a web application that I am trying to "break".There's a login page that requires username and password input. Let's say I have a table Auser that stores username's info in MySQL.
When I hit Login after keying the credentials,it executes this line of code:
String sql = "select object(o) from Auser as o where ausername='" + username + "'";
Now, I know not using preparedStatement makes SQL query vulnerable to SQL injection and I want to perform such a stunt. I created a dummy table called test for the purpose of able to drop this table via the injection command.
I tried various ways like in my username input(root is the username):
root` DROP TABLE test;
And it didn't work. Is there a way to make my injection successful?
Update:
Just extra info, my username column is VARCHAR(255) and my method for getting the username is below:
public Auser get(String username, boolean moreInfo) {
try {
Auser u = null;
String sql = "select object(o) from Auser as o where ausername='" + username + "'";
List resList = em.createQuery(sql).getResultList();
if (resList == null) { // null check for sql query / library error
msg = CoreUtil.wrapMsg(CoreUtil.FUNC_ERROR,
this.getClass().getName(), "get[" + username + "]", "query error AUSER.");
} else if (resList.isEmpty()) {
msg = "User " + username + " not found.";
} else {
u = (Auser) resList.get(0);
}
return u;
} catch (Exception e) {
msg = CoreUtil.wrapMsg(CoreUtil.FUNC_ERROR,
this.getClass().getName(), "get[" + username + "]", e.getMessage());
return null;
}
}
Seems every solution, I tried keeps throwing IllegalArgumetnException and the table still remains.I just want to exploit the vulnerabilities of my program,it can be any kind of injection whether dropping a table, returning all users info,etc.
The EntityManager has some (very) basic protection built in that won't run more than one command in the same SQL statement.
This will protect you from Robert'); DROP TABLE Students; --, but it won't protect from attackers trying to expand/alter the one query that's being run.
For example, in your code an attacker could get the details of another user by entering the username ' OR 1 = 1 --; This would make the SQL string being executed
select object(o) from Auser as o where ausername='' OR 1 = 1 --'
which will select every user in the table (note that the -- at the end of the input will comment out everything after the injected code), and your method will return the first user in the result list This will potentially give the attacker details about another user that they should not have access to. If the first account is an administrator account then they may also have access they should not have.
An attacker can also learn the structure of the table this way - they can try strings like ' and IS_ADMIN = IS_ADMIN --, or ' OR ID = 0 --. If they try enough of these (and attacks like this can be easily automated) they will find valid column names when the query doesn't throw an error. They can potentially then make a more targeted injection attack to gain access to an admin account.
They might also learn things from the error message returned from a failed attempt, such as the DB platform, which can make attacks easier.
String sql = "select object(o) from Auser as o where ausername='" + username + "'";
If you want to delete the test table
username = "x'; DROP TABLE test AND '1'='1"
If you want to see all fields of all ausers entries
username = "x' OR '1'='1"

Can't insert into Sql Server using Spring Framework SimpleJdbcInsert

I'm trying to insert a row in Sql Server 2008 using JDBC Spring framework:
Here is the code:
BdClass bdclass= new BdClass(BdClass.BdConfig.ConnectionString_MYHOME);
Person personaNueva = new Person();
personaNueva.setIdPerson(5);
personaNueva.setUsuario("JavaUser");
personaNueva.setClave("JavaPassword");
personaNueva.setNombre("JavaNombreUsuario");
personaNueva.setActivo("S");
personaNueva.AddPerson(bdclass);
//Person class
public void AddPerson(BdClass bdclass)
{
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put(Constantes.idperson, this.getIdperson());
parameters.put(Constantes.usuario,this.getUsuario());
parameters.put(Constantes.clave,this.getClave());
parameters.put(Constantes.nombre,this.getNombre());
parameters.put(Constantes.activo, this.getActivo());
bdclass.Insert(parameters,Constantes.Table_Name);
}
//BdClass Insert
In this step I am enabling IDENTITY INSERT
public void Insert(Map<String, Object> parameters, String TableName)
{
this.jdbcTemplate.execute("SET IDENTITY_INSERT " + TableName + " ON");
JdbcInsert = new SimpleJdbcInsert(this.jdbcTemplate).withTableName(TableName);
JdbcInsert.execute(parameters);
}
When running the execute statement I am getting the following exception:
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Cannot
insert explicit value for identity column in table 'Persons' when
IDENTITY_INSERT is set to OFF
I have already tried the command SET IDENTITY_INSERT PERSONS ON in sql management studio with no luck.
EDIT: idperson field is identity, but it doesn't matter if I pass the parameter and value or not... I'm getting the same error
EDIT 2:
Ok, I fixed it by using the usingColumns Property, So I can specify every column:
public void Insert(Map<String, Object> parameters, String TableName)
{
this.jdbcTemplate.execute("SET IDENTITY_INSERT " + TableName + " OFF");
JdbcInsert = new SimpleJdbcInsert(this.jdbcTemplate).withTableName(TableName)
.usingColumns(Person.Constantes.usuario,Person.Constantes.clave,
Person.Constantes.nombre,Person.Constantes.activo);
JdbcInsert.execute(parameters);
}
SQL Server's SET IDENTITY is session scoped. That means you must execute the command SET IDENTITY_INSERT " + TableName + " ON" under the same transaction you are using to insert your data.
Spring JDBC Template opens a new connection for each statement, and thats why you are not being able to set it under the same session.
//connection opened --> statement executed --> connection closed
this.jdbcTemplate.execute("SET IDENTITY_INSERT " + TableName + " ON");
I think the best approach is not to the IDENTITY_INSERT ON and do the following:
public void Insert(Map<String, Object> parameters, String TableName)
{
JdbcInsert = new SimpleJdbcInsert(this.jdbcTemplate).withTableName(TableName);
//This column won't be included on the insert statement (it will be autogenerated by SQL Server)
JdbcInsert.setGeneratedKeyName("id");
JdbcInsert.execute(parameters);
}
Another alternative is to execute both statements under the same transaction, but I don't think you could use SimpleJdbcInsert for that.

SQL error Too few parameters

I'm having an sql problem. I writing a java application on top of a Access database.
It's a search query for several fields and I know the error is in the part where I need to calculate the age of a person when he or she went missing. I'm returning a tablemodel in my method so i need to do the calculations in my query. My latest atempt to make it work is this:
public TableModel UpdateTable(String dossiernr, String naam, String voornaam,
String startleeftijd, String eindleeftijd, String dossierjaar, String geslacht)
{
TableModel tb = null;
String sql= "SELECT [Nr dossier],[Annee],[Nom],[Prenom],[Disparu le],[Ne le],[Sexe], DATEDIFF('yyyy',[Ne le],[Disparu le]) - iif(DATEADD('yyyy', DATEDIFF('yyyy',[Ne le],[Disparu le]),"
+ "[Ne le])>[Disparu le],1,0) AS Age FROM TotalTable "
+ "WHERE [Nr dossier] LIKE ? AND [Nom] LIKE ? AND [Prenom] LIKE ? AND [Annee] LIKE ? AND Age >= ? AND Age <= ? AND [Sexe] LIKE ?;";
try
{
PreparedStatement pstatement;
Connection connection = PersistentieController.getInstance().getConnection();
pstatement = initStatement(connection,sql);
pstatement.setString(1, "%" + dossiernr + "%");
pstatement.setString(2, "%" + naam + "%");
pstatement.setString(3, "%" + voornaam + "%");
pstatement.setString(4, "%" + dossierjaar + "%");
pstatement.setString(5, startleeftijd);
pstatement.setString(6, eindleeftijd);
pstatement.setString(7, "%" + geslacht + "%");
rs=pstatement.executeQuery();
tb = DbUtils.resultSetToTableModel(rs);
pstatement.close();
}//einde try
catch (SQLException e)
{
e.printStackTrace();
} //einde catch
return tb;
}
When i run it, i get following error:
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 8.
I only work with 7 parameters and don't get why he's asking for 8.
Thanks
You count 7 parameters in your WHERE clause. Unfortunately, the Access db engine treats Age as another parameter in that situation, so it thinks you have 8 parameters instead of only 7.
To understand why, start with this query which runs without error with my Access database:
SELECT some_text AS foo
FROM tblFoo
WHERE some_text Is Not Null;
However, when attempting to use the alias instead of the field name in the WHERE clause, Access prompts me to supply a value for foo because it treats it as a parameter:
SELECT some_text AS foo
FROM tblFoo
WHERE foo Is Not Null;
Access limits your ability to re-use alias names later in a query. In certain cases, it will accept the alias, but yours is not one of those cases.
You could define the alias in a subquery. Then the db engine will recognize it correctly when you reference the subquery's alias in the parent query.
If possible, test your SQL statements directly in Access. If they fail, that effort will give you the best chance to determine why.

Basic Hibernate Select all Syntax

I am trying to retrieve data from my database with hibernate but it keeps throwing an exception
2012-11-11 11:35:45,943 [main] ERROR
com.storage.hibernate.DatabaseAccessRequestsImpl - there was an error
javax.persistence.PersistenceException:
org.hibernate.exception.SQLGrammarException: could not execute query
#Override
public List<Trade> requestPeriod() {
List<Trade> trades = null;
EntityManager manager = emf.createEntityManager();
Query query = manager.createQuery("from trade");
try{
trades = query.getResultList();
}
catch(PersistenceException e){
logger.error("there was an error " + e);
}
catch(SQLGrammarException e){
logger.error("there was an error " + e);
}
return trades;
}
I am guessing the syntax I am using for select all is incorrect but after looking around I can not see an alternative?
Thanks
It should be "from Trade" (uppercase T) as Trade is the name of the mapped class.
Note that in JPA QL SELECT clause is mandatory, as per: 10.2.1.1. JPQL Select Statement:
A select statement is a string which consists of the following clauses:
a SELECT clause, which determines the type of the objects or values to be selected;
a FROM clause, which provides declarations that designate the domain to which the expressions specified in the other clauses of the query apply;
[...]
In BNF syntax, a select statement is defined as:
select_statement ::= select_clause from_clause [where_clause] [groupby_clause] [having_clause] [orderby_clause]
The bare from Trade syntax is Hibernate-specific, to be specification compliant you should always use:
select t from Trade t

Categories

Resources