HSQL Error: org.hsqldb.HsqlException: primary key already exist - java

I am using the old-school ddlutils lib to create a schema in hsql, and am seeing this error. It is strange because the primary key is only created once.
org.apache.ddlutils.DatabaseOperationException: Error while executing SQL -- -----------------------------------------------------------------------
-- musician
-- -----------------------------------------------------------------------
CREATE TABLE musician
(
id INTEGER IDENTITY,
name VARCHAR(2147483647),
PRIMARY KEY (id)
)
at org.apache.ddlutils.platform.PlatformImplBase.evaluateBatch(PlatformImplBase.java:331)
at org.apache.ddlutils.platform.PlatformImplBase.createTables(PlatformImplBase.java:424)
at org.apache.ddlutils.platform.PlatformImplBase.createTables(PlatformImplBase.java:409)
at my.data.SchemaSync.applySchema(SchemaSync.java:104)
at my.data.SchemaSync.start(SchemaSync.java:42)
at my.deploy.BaseEnvironment$1.run(BaseEnvironment.java:38)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.sql.SQLSyntaxErrorException: primary key already exist
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.fetchResult(Unknown Source)
at org.hsqldb.jdbc.JDBCStatement.executeUpdate(Unknown Source)
at org.apache.ddlutils.platform.PlatformImplBase.evaluateBatch(PlatformImplBase.java:309)
... 6 more
Caused by: org.hsqldb.HsqlException: primary key already exist
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.ParserTable.readConstraint(Unknown Source)
at org.hsqldb.ParserTable.readTableContentsSource(Unknown Source)
at org.hsqldb.ParserTable.compileCreateTableBody(Unknown Source)
at org.hsqldb.ParserTable.compileCreateTable(Unknown Source)
at org.hsqldb.ParserDDL.compileCreate(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatements(Unknown Source)
at org.hsqldb.Session.executeDirectStatement(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 9 more

The simple use of IDENTITY implies a primary key is generated. It is better to use this SQL Standard form:
CREATE TABLE musician
(
id INTEGER GENERATED BY DEFAULT AS IDENTITY,
name VARCHAR(2147483647),
PRIMARY KEY (id)
)
The syntax that caused the error is supported from version 2.3.4

Related

Derby Embedded Database using Authentication

Apache Derby Embedded Database in default manner it doesn't need authentication. We can enable authentication in system level or database level. I made system level enabling using java code.
Properties p=System.getProperties();
p.put("derby.connection.requireAuthentication", "true");
Then I tried create the database using this connection URL.
jdbc:derby:derbysample;create=true;user=root;password=root
When i run this
DriverManager.getConnection(connectionURL);
It creates database folder also throw errors regarding authentication? How to create a database with credentials?
java.sql.SQLNonTransientConnectionException: Connection authentication
failure occurred. Reason: Invalid authentication.. at
org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown
Source) at
org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown
Source) at
org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown
Source) at
org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown
Source) at
org.apache.derby.impl.jdbc.EmbedConnection.checkUserCredentials(Unknown
Source) at org.apache.derby.impl.jdbc.EmbedConnection.(Unknown
Source) at
org.apache.derby.jdbc.InternalDriver.getNewEmbedConnection(Unknown
Source) at org.apache.derby.jdbc.InternalDriver.connect(Unknown
Source) at org.apache.derby.jdbc.InternalDriver.connect(Unknown
Source) at org.apache.derby.jdbc.AutoloadedDriver.connect(Unknown
Source) at
java.sql.DriverManager.getConnection(DriverManager.java:664) at
java.sql.DriverManager.getConnection(DriverManager.java:208) at
derbytest.DerbyTest.createConnection(DerbyTest.java:56) at
derbytest.DerbyTest.main(DerbyTest.java:39) Caused by: ERROR 08004:
Connection authentication failure occurred. Reason: Invalid
authentication.. at
org.apache.derby.iapi.error.StandardException.newException(Unknown
Source) at
org.apache.derby.impl.jdbc.SQLExceptionFactory.wrapArgsForTransportAcrossDRDA(Unknown
Source) ... 15 more
First specify the database URL that you are going to create with properties create=true
jdbc:derby:derbysample111;create=true
Then get Connection using DriverManager. It will create a database if it is not exist.
conn = DriverManager.getConnection("jdbc:derby:derbysample111;create=true");
conn.setSchema("APP");
Then enable authentication in derby and set user and password. It will set database level authentication.
Statement s = conn.createStatement();
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(\n"
+ " 'derby.connection.requireAuthentication', 'true')");
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(\n"
+ " 'derby.authentication.provider', 'BUILTIN')");
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(\n"
+ " 'derby.user.root', '12345')");
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(\n"
+ " 'derby.database.propertiesOnly', 'true')");
It is only need to be set once. Then can access your database using this URL
jdbc:derby:derbysample111;create=true;user=root;password=12345

db.lck appears while compiling a java program using a derby database

Recently I have been trying a lot and scratching everywhere to connect to a derby database using NetBeans 8.0. After a lot of research in SO (link1, link2, link3, link4) and everywhere else I am unable to understand that how to make it go away.I realize this is the reason :-(the db.lck) that I am not getting a connection to the embedded apache derby DB.
I notice that db.lck appears while I compile the Java program. Is that a reason that I am denied to a embedded apache derby connection?
N.B :-1. I connected to the JavaDB Server.2. Disconnected the connection to the DB while compiling the program.3. Added the relevant jar file derby.jar.4. Created the database with default schema APP used username and password both as app.
5. Removed the create=true option from the connection string.
6. I can view and manipulate the data through the SQL console in NetBeans 8.0
Providing the code below for further reference :
test.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class test
{
public static void main(String args [])
{
try {
Connection con = DriverManager.getConnection("jdbc:derby:C:/Users/Dhruvh/Documents/NetBeansProjects/ApacheDerby/derbytest","app","app");
PreparedStatement stmt=con.prepareStatement("select * from \"APP\".TABLE1");
ResultSet rs=stmt.executeQuery();
if(rs.next())
{
System.out.println("Id : "+rs.getInt(1) +" "+" name :"+rs.getString(2));
}
else
{
System.out.println("No word matching in database");
}
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
}
I have also tried using:-
PreparedStatement stmt=con.prepareStatement("select * from APP.TABLE1");
PreparedStatement stmt=con.prepareStatement("select * from TABLE1");
PreparedStatement stmt=con.prepareStatement("select * from app.table1"); //table was created in lower case
But everything I mention above gave the same error:-
Table/View 'APP.TABLE1' does not exist.
StackTrace:
java.sql.SQLSyntaxErrorException: Table/View 'APP.TABLE1' does not exist.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.handleException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement.<init>(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedPreparedStatement42.<init>(Unknown Source)
at org.apache.derby.jdbc.Driver42.newEmbedPreparedStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.prepareStatement(Unknown Source)
at test.main(test.java:12)
Caused by: ERROR 42X05: Table/View 'APP.TABLE1' does not exist.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.FromBaseTable.bindTableDescriptor(Unknown Source)
at org.apache.derby.impl.sql.compile.FromBaseTable.bindNonVTITables(Unknown Source)
at org.apache.derby.impl.sql.compile.FromList.bindTables(Unknown Source)
at org.apache.derby.impl.sql.compile.SelectNode.bindNonVTITables(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLStatementNode.bindTables(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLStatementNode.bind(Unknown Source)
at org.apache.derby.impl.sql.compile.CursorNode.bindStatement(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
Also proving a snapshot of the created DB
Please tell if any further references are needed to solve the problem.
Thanks for you patience
You gave derby location of a database that doesn't exist, so it tries to create the database itself.
jdbc:derby:C:/Users/Dhruvh/Documents/NetBeansProjects/ApacheDerby/src/derbytest;**create=true**
The bold part is a default argument which you leave out in your driver creation.
You can connect to the database but there doesn't exist a table you want to access. You have to fix the location of the database. Also if you are connected to the db through your program(looks like mplab x ?), you need to terminate that connection first.

Generating HSQLDB tables in memory from JPA/EclipseLink (no files)

I have JPA2 with EclipseLink 2.4, and I'm trying to implement an in-memory database using HSQLDB. I have been able to create a file implementation of the hsqldb using
jdbc:hsqldb:file:./databases/test;shutdown=true;files_readonly=true
But when I try to use jdbc:hsqldb:mem:tableName, I get the following message:
Stacktrace:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse
Persistence Services - 2.4.0.v20120608-r11652):
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: user lacks privilege or object
not found: EFFECTIVITY
Error Code: -5501
Call: INSERT INTO EFFECTIVITY (HULL) VALUES (?)
bind => [1 parameter bound]
Query: InsertObjectQuery(101)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush
(EntityManagerImpl.java:804)
at com.gdeb.touchtable.db.TestJPAEntities.testTTTouch(TestJPAEntities.java:93)
..............
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found:
EFFECTIVITY
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.SchemaManager.getTable(Unknown Source)
at org.hsqldb.ParserDQL.readTableName(Unknown Source)
at org.hsqldb.ParserDQL.readRangeVariableForDataChange(Unknown Source)
at org.hsqldb.ParserDML.compileInsertStatement(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)
... 63 more
From what I read, the data model should be generated automagically, but I have only seen examples with Hibernate. Is there a way to link the JPA data-model and create it using the memory mode of HSQLDB?
If what is missing are the tables, you need to set the eclipselink.ddl-generation property with a value of "create-tables" to have Eclipselink create them for you. An example is posted here: http://wiki.eclipse.org/EclipseLink/Examples/JPA/DDL

App Engine / Quercus datastore prepare query error

I'm trying to replicate the java guestbook example on Quercus on AppEngine and I'm getting an error having to do with preparing the query:
$greetings = $datastore->prepare($query)->asIterable();
I'm not a java developer so I can't make sense of the error trace. How can I get the greeting items without triggering this error?
Here is the entire error page:
HTTP ERROR 500
Problem accessing /index.php. Reason:
INTERNAL_SERVER_ERROR
Caused by:
java.lang.NullPointerException at
com.google.appengine.api.datastore.dev.LocalDatastoreService.next(LocalDatastoreService.java:1089)
at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at
java.lang.reflect.Method.invoke(Unknown Source) at
com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.callInternal(ApiProxyLocalImpl.java:498)
at
com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.call(ApiProxyLocalImpl.java:452)
at
com.google.appengine.tools.development.ApiProxyLocalImpl$AsyncApiCall.call(ApiProxyLocalImpl.java:430)
at java.util.concurrent.Executors$PrivilegedCallable$1.run(Unknown
Source) at java.security.AccessController.doPrivileged(Native Method)
at java.util.concurrent.Executors$PrivilegedCallable.call(Unknown
Source) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown
Source) at java.util.concurrent.FutureTask.run(Unknown Source) at
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
If it's a null pointer exception then you are trying to access a method or property of a null object
First you need to check if $datastore is null, then if the return of the query is not null. Also you need to check if that error is on that particular line of code (maybe it fails somewhere else)
You can access the database at this link /_ah/admin. Maybe there is a corrupt entity in there

Dynamically changing number of columns in a JTable

I have a JTable and a TableModel that extends AbstractTableModel. I would like to dynamically set the number of columns in the table. I implemented this by adding an attribute to my TableModel named, column_count, and having getColumnCount return the column_count. I also added a method, setColumnCount, that sets column_count and calls fireTableStructureChanged. Unfortunately, when I ran the program, I kept getting ArrayIndexOutOfBounds exceptions. Can anyone tell me what I did wrong, or suggest a better solution?
Here's a stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4 >= 4
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paintGrid(Unknown Source)
at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source)
at javax.swing.plaf.ComponentUI.update(Unknown Source)
at javax.swing.JComponent.paintComponent(Unknown Source)
at javax.swing.JComponent.paint(Unknown Source)
at javax.swing.JComponent.paintToOffscreen(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source)
at javax.swing.RepaintManager$PaintManager.paint(Unknown Source)
at javax.swing.RepaintManager.paint(Unknown Source)
at javax.swing.JComponent._paintImmediately(Unknown Source)
at javax.swing.JComponent.paintImmediately(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source)
at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
I think the exception is caused as follows:
You set internal column_count to +1
You cause events to be fired which will cause the table to be updated visually
When the JTable update code accesses the last column the internal Vector in the column model throws the exception.
The reason is probably because the underlying code of DefaultTableColumnModel does not know about the new column, and its Vector has not properly been altered.
To fix this you should probably write your own custom TableColumnModel which can deal with changing dimensions properly.
Where does your getValueAt() method takes data? If it is an ArrayList and you increase column size, than the table will try to fetch that column from the list and throw an exception.
If that is not the problem, either use DefaultTableModel and DefaultTableModel.addColumn() to add columns, or make sure that you make any changes to the table model from the Event Dispatch Thread.
Calling to method setModel(tm) of JTable with tm the changed TableModel
solved a similar error in my case.

Categories