Tables created via DDL in UCanAccess cannot be opened in Access itself - java

I have been able to successfully create MS Access database tables from Java using the UCanAccess 2.0.6 driver. However, I am subsequently unable to open up the tables from MS Access (Microsoft Office 2007, Windows 7 64-bit), with MS Access throwing the error :
Reserved Error (-5001); there is no message for this error.
The exact same CREATE TABLE statement when used from within MS Access itself results in no problems. The strange part is, the tables are successfully created and data can be successfully added AND retrieved by query. So the tables are there in the underlying database, but Access isn't able to open them.
If it helps, one of the create statements I'm using is as follows:
CREATE TABLE tblMain (
ID COUNTER NOT NULL PRIMARY KEY,
Project INTEGER NOT NULL,
ItemNumber INTEGER NOT NULL,
DateCreated DATETIME NOT NULL,
ItemName TEXT NOT NULL,
ItemDescription MEMO NOT NULL,
OriginatorPerson TEXT NOT NULL,
DueDate DATETIME NOT NULL,
Closed YESNO NOT NULL,
ClosingComments MEMO NOT NULL,
Priority YESNO NOT NULL,
AssignedToCompany TEXT NOT NULL,
AssignedToPerson TEXT NOT NULL);

I can't reproduce this problem, neither with Access 2007 nor with Access 2010.
All works fine also with Access 2003. But it might happen with some access version...
It looks very similar to an issue that another user reported in the UCanAccess forum and that I fixed (yet, in that case, I wasn't able to reproduce this issue):
http://sourceforge.net/p/ucanaccess/discussion/help/thread/5a57b955/.
I'm pretty sure it's about the way UCanaccess(using the underlying jackcess) persists the column properties (e.g, default values, "required" and so on).
Could you try to re-execute your DDL avoiding to set "not null" where not needed, so on the column ID(Counter and PK)? And please, let me know your findings, I haven't another way to definitively fix this bug.

May be you need to grant privileges to admin:
GRANT SELECT, DELETE, INSERT, UPDATE
ON tblMain
TO Admin;
Run that query using UCanAccess 2.0.6 driver.

Related

SQLite “after update” trigger in Android does not appear to run after every record update

QUESTION:
What, if anything, could cause an SQLite trigger to only run some of the time?
SUMMARY: I'm getting seemingly inconsistent results from a new trigger I've written in SQLite and I'd like to understand if this is happening because I've made a mistake in my SQL/Java code or if I've possibly encountered a rare scenario where SQL triggers may not work as expected.
DETAILS:
While working on an Android project I have encountered what I originally perceived to be a problem with an SQLite trigger. However, since my new trigger exactly matches several other working triggers in the same project (except for the table names) I am beginning to wonder if my Java code is the issue instead.
The purpose of the trigger I am having trouble with is to monitor changes to TableA, such as the addition of a value in the DismissDateUTC column for example. When an update is made to any data in TableA, the trigger is supposed to put the ID of that updated TableA record into TableAChanges which is later used to determine which records were updated and should be sent back to a web server.
When using the database inspector (in Android Studio v4.2.1) or the program “DB Browser for SQLite” and running an update query on TableA manually, the trigger works exactly as expected and records appear in TableAChanges. When I make updates to TableA programmatically, the trigger does not appear to run. I believe it is not running because no records are written to TableAChanges after updates have been written to TableA.
Things I have tried so far:
Running the app on an Android 7.1.1 device (trigger is NOT working)
Running the app on an Android 8.1.0 device (trigger is NOT working)
Running the app on an Android 11 device (trigger is NOT working)
Running manual update query on TableA from Android Studio DB Inspector (trigger IS working)
Running manual update query on TableA from DB Browser for SQLite (trigger IS working)
Running manual update query on TableA from Android Debug Database by “amitshekhar” (trigger IS working)
The Tables and Trigger SQL:
CREATE TABLE TableA (
ID INTEGER PRIMARY KEY NOT NULL
-- (more table columns) --
, DismissDateUTC TEXT NULL
);
CREATE TABLE TableAChanges (
ID INTEGER PRIMARY KEY NOT NULL
);
CREATE TRIGGER trigTableA_U AFTER UPDATE ON TableA
BEGIN
REPLACE INTO TableAChanges(ID)
SELECT old.ID;
END
The Android Java in the TableA DAO class:
public boolean saveChanges() {
boolean ret = true;
ContentValues cv = new ContentValues();
cv.put("ID", mId);
// (more table columns)
cv.put("DismissDateUtc", mDismissDateUtc);
SQLiteDatabase db = DB.getInstance().getWritableDatabase();
try {
db.replaceOrThrow("TableA", null, cv);
} catch (SQLException e) {
ExceptionDao.logToAcra(e);
ret = false;
} finally {
db.close();
}
return ret;
}
*** In the interest of transparency, I am already aware that I can work around this issue by manually writing records to TableAChanges. However, I still wanted to post this question here because I am hoping to gain an understanding of the cause of this issue rather than ignoring the issue.
The reason that the trigger does not work is because it is an AFTER UPDATE trigger, which means that it will work only after the table is updated.
On the other hand, replaceOrThrow() does not update the table.
It is actually executing an INSERT OR REPLACE INTO... or simply REPLACE INTO... statement which either inserts a new row in the table if the new ID does not already exist in the table, or if it exists, deletes the row that contains the existing ID and inserts the new row.

org.hibernate.HibernateException: Missing table exception though MySQL table is present

I am connecting to a MySQL table using JPA Hibernate. But I am getting error in my Java code:
org.hibernate.HibernateException: Missing table
My table is present in MySQL database schema. I am not getting why missing table exception is thrown here. This is a newly created table. All other existing tables in the same schema are accessible from Hibernate. I saw similar posts with same error. But the answers there didn't help my cause. Can you please let me know what can be the issue here.
If table is present, then most likely it is user permission issue. This happens if you have created the table using a different MySQL user. Make sure the MySQL username/password that you are using in Hibernate is having access to the table. To test, login to MySQL console directly using Hibernate credential & run a select query on the table. If you see similar error as below, then you need to grant access to the table for the Hibernate user.
ERROR 1142 (42000): SELECT command denied to user
Source: http://www.w3spot.com/2020/10/how-to-solve-caused-by-hibernateexception-missing-table.html
Make sure the user has access to the table
Make sure names are equals in terms of case sensitivity
Make sure the schema name and table name are not misspelled
If you share more information about the issue, it would be easier to pinpoint the problem.
Chances are there is an inheritance scenario with a physical table that you assumed to be abstract.
To dig deeper you can put a breakpoint in org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl#getTablesInformation which calls extractor.getTable to see why your table is not returned as part of schema tables.
Rerun the app with the specified breakpoint and step through lines to get to the line which queries table names from the database metadat.
#Override
public TableInformation getTableInformation(QualifiedTableName tableName) {
if ( tableName.getObjectName() == null ) {
throw new IllegalArgumentException( "Passed table name cannot be null" );
}
return extractor.getTable(
tableName.getCatalogName(),
tableName.getSchemaName(),
tableName.getTableName()
);
}

hbm2ddl.auto is not creating schema automatically when set to create [duplicate]

I am getting below exception, when trying to insert a batch of rows to an existing table
ORA-00942: table or view does not exist
I can confirm that the table exists in db and I can insert data to that table using oracle
sql developer. But when I try to insert rows using preparedstatement in java, its throwing table does not exist error.
Please find the stack trace of error below
java.sql.SQLException: ORA-00942: table or view does not exist
at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:289)
at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:573)
at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1889)
at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteFetch(TTC7Protocol.java:1093)
at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2047)
at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout>>(OracleStatement.java:2709)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:589)
at quotecopy.DbConnection.insertIntoDestinationDb(DbConnection.java:591)
at quotecopy.QuoteCopier.main(QuoteCopier.java:72)
Can anyone suggest the reasons for this error ?
Update : Issue solved
There was no problem with my database connection properties or with my table or view name. The solution to the problem was very strange. One of the columns that I was trying insert was of Clob type. As I had a lot of trouble handling clob data in oracle db before, gave a try by replacing the clob setter with a temporary string setter and the same code executed with out any problems and all the rows were correctly inserted!!!.
ie. peparedstatement.setClob(columnIndex, clob)
was replaced with
peparedstatement.setString(columnIndex, "String")
Why an error table or view does exist error was throws for error in inserting clob data. Could anyone of you please explain ?
Thanks a lot for your answers and comments.
Oracle will also report this error if the table exists, but you don't have any privileges on it. So if you are sure that the table is there, check the grants.
There seems to be some issue with setCLOB() that causes an ORA-00942 under some circumstances when the target table does exist and is correctly privileged. I'm having this exact issue now, I can make the ORA-00942 go away by simply not binding the CLOB into the same table.
I've tried setClob() with a java.sql.Clob and setCLOB() with an oracle.jdbc.CLOB but with the same result.
As you say, if you bind as a string the problem goes away - but this then limits your data size to 4k.
From testing it seems to be triggered when a transaction is open on the session prior to binding the CLOB. I'll feed back when I've solved this...checking Oracle support.
There was no problem with my database connection properties or with my table or view name. The solution to the problem was very strange. One of the columns that I was trying insert was of Clob type. As I had a lot of trouble handling clob data in oracle db before, gave a try by replacing the clob setter with a temporary string setter and the same code executed with out any problems and all the rows were correctly inserted!!!.
ie. peparedstatement.setClob(columnIndex, clob)
was replaced with
peparedstatement.setString(columnIndex, "String")
#unbeli is right. Not having appropriate grants on a table will result in this error. For what it's worth, I recently experienced this. I was experiencing the exact problem that you described, I could execute insert statements through sql developer but would fail when using hibernate. I finally realized that my code was doing more than the obvious insert. Inserting into other tables that did not have appropriate grants. Adjusting grant privileges solved this for me.
Note: Don't have reputation to comment, otherwise this may have been a comment.
We experienced this issue on a BLOB column. Just in case anyone else lands on this question when encountering this error, here is how we resolved the issue:
We started out with this:
preparedStatement.setBlob(parameterIndex, resultSet.getBlob(columnName)); break;
We resolved the issue by changing that line to this:
java.sql.Blob blob = resultSet.getBlob(columnName);
if (blob != null) {
java.io.InputStream blobData = blob.getBinaryStream();
preparedStatement.setBinaryStream(parameterIndex, blobData);
} else {
preparedStatement.setBinaryStream(parameterIndex, null);
}
I found how to solve this problem without using JDBC's setString() method which limits the data to 4K.
What you need to do is to use preparedStatement.setClob(int parameterIndex, Reader reader). At least this is what that worked for me. Thought Oracle drivers converts data to character stream to insert, seems like not. Or something specific causing an error.
Using a characterStream seems to work for me. I am reading tables from one db and writing to another one using jdbc. And i was getting table not found error just like it is mentioned above. So this is how i solved the problem:
case Types.CLOB: //Using a switch statement for all columns, this is for CLOB columns
Clob clobData = resultSet.getClob(columnIndex); // The source db
if (clobData != null) {
preparedStatement.setClob(columnIndex, clobData.getCharacterStream());
} else {
preparedStatement.setClob(columnIndex, clobData);
}
clobData = null;
return;
All good now.
Is your script providing the schema name, or do you rely on the user logged into the database to select the default schema?
It might be that you do not name the schema and that you perform your batch with a system user instead of the schema user resulting in the wrong execution context for a script that would work fine if executed by the user that has the target schema set as default schema. Your best action would be to include the schema name in the insert statements:
INSERT INTO myschema.mytable (mycolums) VALUES ('myvalue')
update: Do you try to bind the table name as bound value in your prepared statement? That won't work.
It works for me:
Clob clob1;
while (rs.next()) {
rs.setString(1, rs.getString("FIELD_1"));
clob1 = rs.getClob("CLOB1");
if (clob1 != null) {
sta.setClob(2, clob1.getCharacterStream());
} else {
sta.setClob(2, clob1);
}
clob1 = null;
sta.setString(3, rs.getString("FIELD_3"));
}
Is it possible that you are doing INSERT for VARCHAR but doing an INSERT then an UPDATE for CLOB?
If so, you'll need to grant UPDATE permissions to the table in addition to INSERT.
See https://stackoverflow.com/a/64352414/1089967
Here I got the solution for the question. The problem is on glass fish if you are using it. When you create JNDI name make sure pool name is correct and pool name is the name of connection pool name that you are created.

How to force treat MySQL Constraint Errors from Hibernate

I have a Java Web Project that uses Hibernate and MySQL. I have trouble to treat exceptions like when i try to insert a new register at database with the same primary key (Intentionally)
i got the following error with a message box "Could not insert:...". But i don't want to shows directly to user this error, i want to treat when i call "Persisten.save()", but in my code it doesn't appears nothing wrong (for my ide, i threat all possible excepetions).
So how can i change (configuration/code) to force threat exceptions like that and change the message?!
You should check if the Id already exists in the database before you try to persist it.

Spring's JdbcDaoSupport (using MySQL Connector/J) fails after executing sql that adds FK

I am using Spring's JdbcDaoSupport class with a DriverManagerDataSource using the MySQL Connector/J 5.0 driver (driverClassName=com.mysql.jdbc.driver). allowMultiQueries is set to true in the url.
My application is an in-house tool we recently developed that executes sql scripts in a directory one-by-one (allows us to re-create our schema and reference table data for a given date, etc, but I digress). The sql scripts sometime contain multiple statements (hence allowMultiQueries), so one script can create a table, add indexes for that table, etc.
The problem happens when including a statement to add a foreign key constraint in one of these files. If I have a file that looks like...
--(column/constraint names are examples)
CREATE TABLE myTable (
fk1 BIGINT(19) NOT NULL,
fk2 BIGINT(19) NOT NULL,
PRIMARY KEY (fk1, fk2)
);
ALTER TABLE myTable ADD CONSTRAINT myTable_fk1
FOREIGN KEY (fk1)
REFERENCES myOtherTable (id)
;
ALTER TABLE myTable ADD CONSTRAINT myTable_fk2
FOREIGN KEY (fk2)
REFERENCES myOtherOtherTable (id)
;
then JdbcTemplate.execute throws an UncategorizedSqlException with the following error message and stack trace:
Exception in thread "main" org.springframework.jdbc.UncategorizedSQLException: StatementCallback; uncategorized SQLException for SQL [ THE SQL YOU SEE ABOVE LISTED HERE ];
SQL state [HY000]; error code [1005]; Can't create table 'myDatabase.myTable' (errno: 150); nested exception is java.sql.SQLException: Can't create table 'myDatabase.myTable' (errno: 150)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
and the table and foreign keys are not inserted.
Also, especially weird: if I take the foreign key statements out of the script I showed above and then place them in their own script that executes after (so I now have 1 script with just the create table statement, and 1 script with the add foreign key statements that executes after that) then what happens is:
tool executes create table script, works fine, table is created
tool executes add fk script, throws the same exception as seen above (except errno=121 this time), but the FKs actually get added (!!!)
In other words, when the create table/FK statements are in the same script then the exception is thrown and nothing is created, but when they are different scripts a nearly identical exception is thrown but both things get created.
Any help on this would be greatly appreciated. Please let me know if you'd like me to clarify anything more.
Some more info:
1) This only happens on my box. My coworker does not get the same problem.
2) The script that forces the tool to error works fine when executed from the mysql command line using the "script" command
My God.
http://bugs.mysql.com/bug.php?id=41635
and
[2nd link removed because spam filter isn't letting me add 2 links. Search Google for "mysql connector / j errno 150" and it's the 3rd result]
...
Looks like mySql5.1 has a bug with its jdbc connector where it bombs where an alter statement to add a FK is in a script with any other statement.
When I broke out my 3 statements into 3 scripts, it worked (the way I was trying before with the 2 fk statements in their own script still bombed because they were sharing a script!!). Also, my coworker is using MySql5.0, so it didn't affect him.
Holy Cow, that was a fun 5 hours.

Categories