Failing jdbc INSERT INTO statement to MS Access database - sql

statement.executeUpdate("INSERT INTO countrylookup (Country, DialCode) VALUES('Iran', '957')")
Running this statement gives me no error output in the console, but when I check the database no update/insert is made. What could be the reason for this?
The access to the database itself is successful, and fetching values with a statement such as SELECT * FROM countrylookup succeeds.
I tried the preparedStatement approach aswell with the exact same result. The file is not open when I execute the command.
UPDATE: Stacktrace: (first row in Swedish means "INSERT INTO-expression contains the following unknown fieldname: 'Pa_RaM000'. Please check that the name is rightly spelled and try again.)
Exception in thread "main" java.sql.SQLException: [Microsoft][Drivrutin f?r ODBC Microsoft Access] INSERT INTO-uttrycket inneh?ller f?ljande ok?nda f?ltnamn: 'Pa_RaM000'. Kontrollera att namnet ?r r?ttstavat och f?rs?k igen.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(Unknown Source)
at MDBAccessor.insertValueIntoField(MDBAccessor.java:43)
at TestRunner.main(TestRunner.java:28)

Is dialcode numeric? If so, remove the quotes from the value.
VALUES('Iran', 957)

In order for the INSERT INTO statement to actually be reflected in the database you have to call connection.commit() followed by connection.close(). Another similar thread describing this: Java General Error On Insert...???

Related

[Amazon](500310) Invalid operation: Assert

I am using spark-redshift and querying redshift data using pyspark for processing.
The query works fine if i run on redshift using workbench etc.But spark-redshift unloads data to s3 and then retrieves it and it is throwing the following error when i run it.
py4j.protocol.Py4JJavaError: An error occurred while calling o124.save.
: java.sql.SQLException: [Amazon](500310) Invalid operation: Assert
Details:
-----------------------------------------------
error: Assert
code: 1000
context: !AmLeaderProcess -
query: 583860
location: scheduler.cpp:642
process: padbmaster [pid=31521]
-----------------------------------------------;
at com.amazon.redshift.client.messages.inbound.ErrorResponse.toErrorException(ErrorResponse.java:1830)
at com.amazon.redshift.client.PGMessagingContext.handleErrorResponse(PGMessagingContext.java:822)
at com.amazon.redshift.client.PGMessagingContext.handleMessage(PGMessagingContext.java:647)
at com.amazon.jdbc.communications.InboundMessagesPipeline.getNextMessageOfClass(InboundMessagesPipeline.java:312)
at com.amazon.redshift.client.PGMessagingContext.doMoveToNextClass(PGMessagingContext.java:1080)
at com.amazon.redshift.client.PGMessagingContext.getErrorResponse(PGMessagingContext.java:1048)
at com.amazon.redshift.client.PGClient.handleErrorsScenario2ForPrepareExecution(PGClient.java:2524)
at com.amazon.redshift.client.PGClient.handleErrorsPrepareExecute(PGClient.java:2465)
at com.amazon.redshift.client.PGClient.executePreparedStatement(PGClient.java:1420)
at com.amazon.redshift.dataengine.PGQueryExecutor.executePreparedStatement(PGQueryExecutor.java:370)
at com.amazon.redshift.dataengine.PGQueryExecutor.execute(PGQueryExecutor.java:245)
at com.amazon.jdbc.common.SPreparedStatement.executeWithParams(Unknown Source)
at com.amazon.jdbc.common.SPreparedStatement.execute(Unknown Source)
at com.databricks.spark.redshift.JDBCWrapper$$anonfun$executeInterruptibly$1.apply(RedshiftJDBCWrapper.scala:108)
at com.databricks.spark.redshift.JDBCWrapper$$anonfun$executeInterruptibly$1.apply(RedshiftJDBCWrapper.scala:108)
at com.databricks.spark.redshift.JDBCWrapper$$anonfun$2.apply(RedshiftJDBCWrapper.scala:126)
at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
Caused by: com.amazon.support.exceptions.ErrorException: [Amazon](500310) Invalid operation: Assert
The query which gets generated:
UNLOAD ('SELECT “x”,”y" FROM (select x,y from table_name where
((load_date=20171226 and hour>=16) or (load_date between 20171227 and
20171226) or (load_date=20171227 and hour<=16))) ') TO ‘s3:s3path' WITH
CREDENTIALS ‘aws_access_key_id=xxx;aws_secret_access_key=yyy' ESCAPE
MANIFEST
What is the issue here and how can i resolve this.
Assert error usually happens when something is wrong with interpreting data types, for example for 2 parts of union query where column N in one part is varchar and in another part the same column is integer or null. Maybe your assertion error happens for data that comes from different nodes (just like in union query). Try to add explicit data formatting for each column like x::integer

JDBC | SQL Anywhere Error -188: Not enough values for host variables

JDBC or Hibernate is showing strange behavior while calling a stored procedure.
Here is the sample code:
return session.createSQLQuery("select * from pr_ss_coo_10x('31748','NEWRX',null,'5053')")
..
....tolist();
It is throwing error
Caused by: org.hibernate.exception.SQLGrammarException: could not execute query
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.loader.Loader.doList(Loader.java:2620)
at org.hibernate.loader.Loader.doList(Loader.java:2600)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429)
at org.hibernate.loader.Loader.list(Loader.java:2424)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1967)
at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
at com.mps.surescript.repository.impl.SSGetInfoRepoImpl.getBenefitCoordInformation(SSGetInfoRepoImpl.java:79)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 76 common frames omitted
Caused by: com.sybase.jdbc3.jdbc.SybSQLException: SQL Anywhere Error -188: Not enough values for host variables
at com.sybase.jdbc3.tds.Tds.a(Unknown Source)
at com.sybase.jdbc3.tds.Tds.nextResult(Unknown Source)
However, it is working fine when I fire the same query through SQL Anywhere client. Sybase error code document says
"You have not provided enough host variables for either the number of
bind variables, or the statement, or the number of SELECT list items."
I have checked it twice and the result set is correctly mapped with the Pojo. What can be the possible root cause for this problem?
Bypassing the Hibernate transaction Management did the trick and fetching result set using PreparedStatement.
Connection con = DriverManager.getConnection(url, user, password);
PreparedStatement ps = con.prepareStatement(
"select * from pr_ss_coo_10x(#param1=?,#param2=?, #param3=?, #param4=? )");
ResultSet rs = ps.executeQuery();
This is not a solution, it is just a way around.

Junit HSQLDB - user lacks privilege or object not found - THIS_.oh-ordnbr

I am getting an exception when my column name contains hyphen "-"
Entity : this is the entity name.
#Entity
#Table(name = "RequestHeader")
public class RequestHeader implements Serializable {
....
....
#Column(name = "`oh-ordnbr`")
private Integer ohOrdnbr;
Schema definition: This is the query for schema creation.
CREATE MEMORY TABLE PUB.REQUESTHEADER(
REQUESTID INTEGER,
IMUSERID INTEGER,
REQUESTDATE DATE,
REQUESTTIME INTEGER,
REQUESTSTATUS VARCHAR(19),
REQUESTTYPE VARCHAR(22),
HEADERINSTRUCTIONS VARCHAR(5150),
DATEFORMAT VARCHAR(20),
TIMEFORMAT VARCHAR(20),
LANGUAGEID INTEGER,
"OH-ORDNBR" INTEGER,
"OH-TRCNSTAMP" INTEGER,
ISPICKUPLIST BIT(1),
CONSTRAINT "RQH-1" PRIMARY KEY(REQUESTID)
);
The error is below:
Exception Stack: Error message which I have received by running the Junit.
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found: THIS_.oh-ordnbr
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.ExpressionColumn.checkColumnsResolved(Unknown Source)
at org.hsqldb.QueryExpression.resolve(Unknown Source)
at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
at org.hsqldb.Session.compileStatement(Unknown Source)
at org.hsqldb.StatementManager.compile(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
Could some one help me in fixing this?
The reason for the object not found error is the fact that the oh-ordnbr column is defined to be case sensitive (this is due to the double quotes you put around it).
You have two possible solutions:
Do not use dashes (hyphens) in your SQL. It is bad practice anyway, use underscores instead.
Update the JPA annotation as follows:
#Column(name = "`OH-ORDNBR`")
private Integer ohOrdnbr;
I strongly recommend using underscores instead of dashes, you never know what weirdness different JPA implementations might have when using the second solution.
Check your configuration file has correct provider, I fixed same issue by providing org.hibernate.ejb.HibernatePersistence provider.
If HSQL Scripts are run via Java and if any new table query is followed by select/alter/update queries it always throws "user lacks privilege object". In reality the create queries after execution with Java Statements never gets commited into the DB and it is not persisted and we run our select/alter/update and it results in the exception. If we run the queries line by line and commit for each line, we could avoid this error.

Exporting an HSQLDB to XML using DBUnit results in null pointer errors

I'm trying to export the entire contents of my database, an HSQLDB, to XML using DBUnit, and I'm getting null pointer errors that I can't understand. I'm following the example in the FAQ:
IDatabaseConnection xmlConnection = new DatabaseConnection(conn);
IDataSet allTables = xmlConnection.createDataSet();
XmlDataSet.write(allTables, new FileOutputStream(DATABASE_PATH + ".xml"));
The null pointer error occurs on the last line. conn and DATABASE_PATH aren't null as they're both checked for that and used later in the program without a problem (exporting the database into CSV using OpenCSV, which works perfectly and exactly as expected).
The stacktrace is as follows:
org.dbunit.dataset.DataSetException: java.sql.SQLException: java.lang.NullPointerException java.lang.NullPointerException
at org.dbunit.database.DatabaseDataSet.initialize(DatabaseDataSet.java:243)
at org.dbunit.database.DatabaseDataSet.getTableNames(DatabaseDataSet.java:272)
at org.dbunit.database.DatabaseDataSet.createIterator(DatabaseDataSet.java:258)
at org.dbunit.dataset.AbstractDataSet.iterator(AbstractDataSet.java:189)
at org.dbunit.dataset.stream.DataSetProducerAdapter.(DataSetProducerAdapter.java:63)
at org.dbunit.dataset.xml.XmlDataSetWriter.write(XmlDataSetWriter.java:128)
at org.dbunit.dataset.xml.XmlDataSet.write(XmlDataSet.java:104)
at org.dbunit.dataset.xml.XmlDataSet.write(XmlDataSet.java:91)
at pms.DatabaseExporter.exportToXML(DatabaseExporter.java:181)
at pms.DatabaseExporter.main(DatabaseExporter.java:301)
Caused by: java.sql.SQLException: java.lang.NullPointerException java.lang.NullPointerException
at org.hsqldb.jdbc.Util.sqlException(Util.java:224)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(JDBCStatement.java:1830)
at org.hsqldb.jdbc.JDBCStatement.executeQuery(JDBCStatement.java:181)
at org.hsqldb.jdbc.JDBCDatabaseMetaData.execute(JDBCDatabaseMetaData.java:6150)
at org.hsqldb.jdbc.JDBCDatabaseMetaData.getTables(JDBCDatabaseMetaData.java:3170)
at org.dbunit.database.DefaultMetadataHandler.getTables(DefaultMetadataHandler.java:137)
at org.dbunit.database.DatabaseDataSet.initialize(DatabaseDataSet.java:199)
... 9 more
Caused by: org.hsqldb.HsqlException: java.lang.NullPointerException
at org.hsqldb.error.Error.error(Error.java:108)
at org.hsqldb.result.Result.newErrorResult(Result.java:1069)
at org.hsqldb.StatementDMQL.execute(StatementDMQL.java:192)
at org.hsqldb.Session.executeCompiledStatement(Session.java:1315)
at org.hsqldb.Session.executeDirectStatement(Session.java:1206)
at org.hsqldb.Session.execute(Session.java:990)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(JDBCStatement.java:1822)
... 14 more
Caused by: java.lang.NullPointerException
at org.hsqldb.types.CharacterType.compare(CharacterType.java:418)
at org.hsqldb.index.IndexAVL.compareRowForInsertOrDelete(IndexAVL.java:617)
at org.hsqldb.index.IndexAVLMemory.insert(IndexAVLMemory.java:214)
at org.hsqldb.persist.RowStoreAVL.indexRow(RowStoreAVL.java:171)
at org.hsqldb.persist.RowStoreAVLHybridExtended.indexRow(RowStoreAVLHybridExtended.java:99)
at org.hsqldb.Table.insertSys(Table.java:2625)
at org.hsqldb.dbinfo.DatabaseInformationMain.SYSTEM_TABLES(DatabaseInformationMain.java:2353)
at org.hsqldb.dbinfo.DatabaseInformationMain.generateTable(DatabaseInformationMain.java:348)
at org.hsqldb.dbinfo.DatabaseInformationFull.generateTable(DatabaseInformationFull.java:379)
at org.hsqldb.dbinfo.DatabaseInformationMain.setStore(DatabaseInformationMain.java:507)
at org.hsqldb.persist.PersistentStoreCollectionSession.getStore(PersistentStoreCollectionSession.java:138)
at org.hsqldb.Table.getRowStore(Table.java:2817)
at org.hsqldb.RangeVariable$RangeIteratorMain.(RangeVariable.java:939)
at org.hsqldb.RangeVariable$RangeIteratorMain.(RangeVariable.java:917)
at org.hsqldb.RangeVariable.getIterator(RangeVariable.java:770)
at org.hsqldb.QuerySpecification.buildResult(QuerySpecification.java:1293)
at org.hsqldb.QuerySpecification.getSingleResult(QuerySpecification.java:1245)
at org.hsqldb.QuerySpecification.getResult(QuerySpecification.java:1235)
at org.hsqldb.StatementQuery.getResult(StatementQuery.java:66)
at org.hsqldb.StatementDMQL.execute(StatementDMQL.java:190)
... 18 more
I've googled and couldn't find anything relating to this kind of error during export. I'm not that experienced with SQL or JDBC so I'm hoping there's enough info in the stack trace for someone more knowledgeable to tell me what's going wrong. If there's some other library that would be better for my needs, I have no problem switching... The only thing I need is export/import with XML right now, so I'm not using DBUnit for anything else. Anyway if anybody can tell me what's going on wrong or if I ought to be using something else I'd really appreciate it.
This is an error in the particular version of HSQLDB's system table creation, which was spotted and corrected recently. You can try the updated HSQLDB jar from http://hsqldb.org/support/

how to resolve org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback;

I am using HSQLDB as my database. i want to get a primary key of latest inserted row. for that i have return a query in my java class as below:
final String query = "INSERT INTO polling_log (start_date,status,action) VALUES(CURRENT_TIMESTAMP,?,?); CALL IDENTITY();";
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
int update = adapterJdbcTemplate.update(new PreparedStatementCreator() {
#Override
public PreparedStatement createPreparedStatement(
Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection
.prepareStatement(query);
preparedStatement.setInt(1, pollingLogVO.getStatus());
preparedStatement.setString(2, pollingLogVO.getAction());
System.out.println(preparedStatement.getGeneratedKeys().getFetchSize());
return preparedStatement;
}
}, generatedKeyHolder);
System.out.println("###################### "+ update);
Number logId = generatedKeyHolder.getKey();
pollingLogId = logId.intValue();
and to store the query i have used GeneratedKeyHolder. but while runing this i get an exception:
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar []; nested exception is java.sql.SQLException: unexpected token: IDENTITY
at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:98)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:602)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:817)
at com.platysgroup.lmex.adapter.moodle.dao.LogDao.insertPollingLog(LogDao.java:36)
at com.platysgroup.lmex.adapter.MoodlePostingTask.insertPollingLog(MoodlePostingTask.java:134)
at com.platysgroup.lmex.adapter.MoodlePostingTask.run(MoodlePostingTask.java:55)
at java.util.TimerThread.mainLoop(Timer.java:512)
at java.util.TimerThread.run(Timer.java:462)
Caused by: java.sql.SQLException: unexpected token: IDENTITY
at org.hsqldb.jdbc.Util.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source)
at org.apache.commons.dbcp.DelegatingConnection.prepareStatement(DelegatingConnection.java:248)
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.prepareStatement(PoolingDataSource.java:302)
at com.platysgroup.lmex.adapter.moodle.dao.LogDao$1.createPreparedStatement(LogDao.java:41)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:580)
... 6 more
Caused by: org.hsqldb.HsqlException: unexpected token: IDENTITY
at org.hsqldb.error.Error.parseError(Unknown Source)
at org.hsqldb.ParserBase.unexpectedToken(Unknown Source)
at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
at org.hsqldb.Session.compileStatement(Unknown Source)
at org.hsqldb.StatementManager.compile(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 12 more
The problem is with this line (wrapped for clarity):
final String query = "INSERT INTO polling_log (start_date,status,action) VALUES(CURRENT_TIMESTAMP,?,?); CALL IDENTITY();";
The issue is that IDENTITY is a reserved word in SQL; it's got a meaning pre-defined already and so can't be used like that in a CALL statement. (I don't know what it is actually used for; the full definition of SQL is huge and has a very large number of reserved words.) The immediate work around would be to enclose the problem word in double quotes (which would need to be backslash-quoted because of being in a Java string):
final String query = "INSERT INTO polling_log (start_date,status,action) VALUES(CURRENT_TIMESTAMP,?,?); CALL \"IDENTITY\"();";
However, if you're just calling that to get the inserted row, STOP! Just let Spring do the work for you, assuming you have JDBC 3.0 or later (i.e., Java 5 or later).
As far as I know you cannot put more than one statements into one string to be executed. Execute two separate operations instead of this.
The following link has what you need:
http://www.devdaily.com/blog/post/jdbc/spring-jdbc-insert-auto-generated-key