insertion records in MS access database - java

I'm trying to insert a large amount of records in my inverted index which has built as table in MS access database. This is table design (ID,term,doc,sent is compound primary key):
and this is the code:
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://myDB.accdb");
Statement s = conn.createStatement();
s.execute("DELETE FROM invertedIndex");
for(String o : POSoutputs) //while (Tokenizer.hasMoreTokens())
{
String word = o;
s.execute("insert into invertedIndex (term,doc,sent) values ('"+ o + "','" + listOfFiles[i].getAbsolutePath() + "','" + fileText + "')");
conn.commit();// i do commit to empty the stack because i will insert thousands of records, by scanning hundreds of documents.
}
This is the Error:
java.lang.StackOverflowError
at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:297)
at java.nio.ByteBuffer.put(ByteBuffer.java:832)
at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:379)
at java.nio.DirectByteBuffer.put(DirectByteBuffer.java:342)
at sun.nio.ch.IOUtil.write(IOUtil.java:60)
at sun.nio.ch.FileChannelImpl.writeInternal(FileChannelImpl.java:778)
at sun.nio.ch.FileChannelImpl.write(FileChannelImpl.java:761)
at com.healthmarketscience.jackcess.impl.PageChannel.allocateNewPage(PageChannel.java:350)
at com.healthmarketscience.jackcess.impl.TempPageHolder.setNewPage(TempPageHolder.java:115)
at com.healthmarketscience.jackcess.impl.UsageMap$ReferenceHandler.createNewUsageMapPage(UsageMap.java:763)
at com.healthmarketscience.jackcess.impl.UsageMap$ReferenceHandler.addOrRemovePageNumber(UsageMap.java:747)
at com.healthmarketscience.jackcess.impl.UsageMap.removePageNumber(UsageMap.java:337)
at com.healthmarketscience.jackcess.impl.PageChannel.allocateNewPage(PageChannel.java:354)
at com.healthmarketscience.jackcess.impl.TempPageHolder.setNewPage(TempPageHolder.java:115)
at com.healthmarketscience.jackcess.impl.UsageMap$ReferenceHandler.createNewUsageMapPage(UsageMap.java:763)
at com.healthmarketscience.jackcess.impl.UsageMap$ReferenceHandler.addOrRemovePageNumber(UsageMap.java:747)
at com.healthmarketscience.jackcess.impl.UsageMap.removePageNumber(UsageMap.java:337)
at com.healthmarketscience.jackcess.impl.PageChannel.allocateNewPage(PageChannel.java:354)
at com.healthmarketscience.jackcess.impl.TempPageHolder.setNewPage(TempPageHolder.java:115)
........ ERROR RECORDS ARE DUPLICATED .. etc
what's the problem?

The error is clear: ERROR RECORDS ARE DUPLICATED
So you have a unique index on one or more fields. Either remove this or remove the records with duplicate field values.

The database was corrupted, i have created another one with the same tables ..
I think the reason is because the answered query in this question: How to restart counting from 1 after erasing table in MS Access?, which have damage the structural indices of the database.
A similar issue is in: deleting row with BigIndex UsageMap exception

Related

Getting duplicate key exception while doing JDBC transaction

I'm trying to add designation and its salary using a JDBC transaction.
The problem is this throws an exception about duplicate key.
This is the first time I put some invalid data in salary columns and after that everything is correct. It shows duplicate key exception for designation id
but the designation id is not stored already and not even for first attempt.
The first transaction that is invalid is rolled back, but storing on next time it shows duplicate key exception.
Below is my code:-
public boolean addDesignation(ObservableList nodeList) throws SQLException {
Connection demo = getConnection();
demo.setAutoCommit(false);
Savepoint savePoint = demo.setSavepoint("savePoint");
try {
PreparedStatement addDesig = demo.prepareStatement(
"INSERT INTO `designation`(`desig_id`,`dept_id`,`desig_name`,`desig_desc`) VALUES (?,?,?,?)");
PreparedStatement addSal = demo.prepareStatement("INSERT INTO `salary` "
+ "(`desig_id`, `basic`, `house_rent`, `conveyance`, `medical`, `dearness`,`others_allowances`,"
+ " `income_tax`, `pro_tax`, `emp_state_insu`, `absence_fine`, `others_deductions`, `month`)"
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
addDesig.setString(1 , nodeList.get(0).toString());
addDesig.setString(2, nodeList.get(1).toString());
addDesig.setString(3, nodeList.get(2).toString());
addDesig.setString(4, nodeList.get(3).toString());
addDesig.executeUpdate();
addSal.setString(1, nodeList.get(0).toString());
addSal.setInt(2, Integer.parseInt(nodeList.get(4).toString()));
addSal.setInt(3, Integer.parseInt(nodeList.get(5).toString()));
addSal.setInt(4, Integer.parseInt(nodeList.get(6).toString()));
addSal.setInt(5, Integer.parseInt(nodeList.get(7).toString()));
addSal.setInt(6,Integer.parseInt(nodeList.get(8).toString()));
addSal.setInt(7,Integer.parseInt(nodeList.get(9).toString()));
addSal.setInt(8, Integer.parseInt(nodeList.get(10).toString()));
addSal.setInt(9, Integer.parseInt(nodeList.get(11).toString()));
addSal.setInt(10, Integer.parseInt(nodeList.get(12).toString()));
addSal.setInt(11, Integer.parseInt(nodeList.get(13).toString()));
addSal.setInt(12, Integer.parseInt(nodeList.get(14).toString()));
addSal.setString(13, nodeList.get(15).toString());
addSal.executeUpdate();
demo.commit();
return true;
} catch (SQLException ex) {
demo.rollback(savePoint);
Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
these are two tables and im trying to add that data in my first attempt failed but not store due roll back
There are 2 INSERT statements in your code.
The 1st for designation table:
"INSERT INTO `designation`(`desig_id`,`dept_id`,`desig_name`,`desig_desc`) VALUES (?,?,?,?)"
here it looks like desig_id is the primary key (maybe autoincrement in which case you must not supply a value at all).
Are you sure the value that you supply for this column does not already exist in the table?
The 2nd for the salary table:
"INSERT INTO `salary` " + "(`desig_id`, `basic`, `house_rent`, `conveyance`, `medical`, `dearness`,`others_allowances`," + " `income_tax`, `pro_tax`, `emp_state_insu`, `absence_fine`, `others_deductions`, `month`)" + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"
in this case it is not clear since you did not post the CREATE statement of the table, which is the primary key.
So you have to check, if the value (or values if it's a multi column key), violate the uniqueness of the key.

SQL Update field without unique index fields

I have table without unique index tuples, lets say table has records
A->B->Status
A->C->Status
A->B->Status
A->B->Status
A->C->Status
I am getting first and second record, processing them. After then I want to update only these two records
how can I make this process possible at java application layer?
Since there is not any unique index tupples I cannot use update SQL with proper WHERE clause
Using
Spring 3.XX
Oracle 11g
I think you may try to use ROWID pseudocolumn.
For each row in the database, the ROWID pseudocolumn returns the address of the row. Oracle Database rowid values contain information necessary to locate a row:
The data object number of the object
The data block in the datafile in which the row resides
The position of the row in the data block (first row is 0)
The datafile in which the row resides (first file is 1). The file
number is relative to the tablespace.
Usually, a rowid value uniquely identifies a row in the database. However, rows in different tables that are stored together in the same cluster can have the same rowid.
SELECT ROWID, last_name
FROM employees
WHERE department_id = 20;
The rowid for the row stays the same, even when the row migrates.
You can solve this issue by using updatable resultsets. This feature relies on rowid to perform all modifications (delete/update/insert).
This is a excerpt highlighting the feature itself:
String sqlString = "SELECT EmployeeID, Name, Office " +
" FROM employees WHERE EmployeeID=1001";
try {
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(sqlString);
//Check the result set is an updatable result set
int concurrency = rs.getConcurrency();
if (concurrency == ResultSet.CONCUR_UPDATABLE) {
rs.first();
rs.updateString("Office", "HQ222");
rs.updateRow();
} else {
System.out.println("ResultSet is not an updatable result set.");
}
rs.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
Here is a complete example.

Mysql JDBC - not entering ResultSet + incorrect no. of rows

I came across a problem with going through a ResultSet I'm generating from my MySQL db. My query should return at most one row per table (I'm looping through several tables searching by employee number). I've entered data in some of the tables; but my test o/p says that the resultset contains 0 rows and doesn't go through the ResultSet at all. The o/p line it's supposed to print never appears. It was in a while loop before I realised that it'd be returning at most one row, at which point I just swapped the while(rs.next()) for an if(rs.first()). Still no luck. Any suggestions?
My code looks like this:
try
{
rsTablesList = stmt.executeQuery("show tables;");
while(rsTablesList.next())
{
String tableName = rsTablesList.getString(1);
//checking if that table is a non-event table; loop is skipped in such a case
if(tableName.equalsIgnoreCase("emp"))
{
System.out.println("NOT IN EMP");
continue;
}
System.out.println("i'm in " + tableName); //tells us which table we're in
int checkEmpno = Integer.parseInt(empNoLbl.getText()); //search key
Statement s = con.createStatement();
query = "select 'eventname','lastrenewaldate', 'expdate' from " + tableName + " where 'empno'=" + checkEmpno + ";"; // eventname,
System.out.println("query is \n\t" + query + "");
rsEventDetails = s.executeQuery(query) ;
System.out.println("query executed\n");
//next two lines for the number of rows
rsEventDetails.last();
System.out.println("no. of rows is " + rsEventDetails.getRow()+ "\n\n");
if(rsEventDetails.first())
{
System.out.println("inside the if");
// i will add the row now
System.out.println("i will add the row now");
// cdTableModel.addRow(new Object[] {evtname,lastRenewalDate,expiryDate});
}
}
}
My output looks like this:
I'm in crm
query is
select 'eventname','lastrenewaldate', 'expdate' from crm where 'empno'=17;
query executed
no. of rows is 0
I'm in dgr
query is
select 'eventname','lastrenewaldate', 'expdate' from dgr where 'empno'=17;
query executed
no. of rows is 0
NOT IN EMP
I'm in eng_prof
query is
select 'eventname','lastrenewaldate', 'expdate' from eng_prof where 'empno'=17;
query executed
no. of rows is 0
I'm in frtol
query is
select 'eventname','lastrenewaldate', 'expdate' from frtol where 'empno'=17;
query executed
no. of rows is 0
(and so on, upto 17 tables.)
The '17' in the query is the empno that I've pulled from the user.
The thing is that I've already entered data in the first two tables, crm and dgr. The same query in the command line interface works; this morning, I tried the program out and it returned data for the one table that had data in it (crm). The next time onwards, nothing.
Context: I'm working on a school project to create some software for my dad's office, it'll help them organise the training etc schedules for the employees. (a little like Google Calendar I guess.) I'm using Netbeans and Mysql on Linux Mint. There are about 17 tables in the database. The user selects an employee name and the program searches for all entries in the database that correspond to an 'event' (my generic name for a test/training/other required event) and puts them into a JTable.
The single quotes around the column names and table name in the creation of the query seem to have caused the problem. On changing them to backticks, retrieval works fine and the data comes in as expected.
Thank you, #juergend (especially for the nice explanation) and #nailgun!

colown count does not match value count at row 1

i am a beginner in java Desktop application, and i was trying to insert some data into my table and i get the following reply "colown count does not match value count at row 1" here is my query
String sql = "insert into cataloguetb(title_statement,aurthurs_name,edition_statement,book_title,publisher_name"
+ "place_of_publication,year_of_publication,isbn_no,index_no,pagenRomannuem,pagneArabi,illuss,size_of_book"
+ "otherAurthurs,addEntries,length_in_cm,accessionNO,call_No1,call_No2,call_No,call_No4)values ('"+(titleStatement)+"','"+(aurthursName)+"'"
+ "'"+(editionStatement)+"','"+(bookTitle)+"','"+(publisherName)+"','"+(placeOfPublication)+"','"+(yearOfPublication)+"'"
+ "'"+(isbnNo)+"','"+(indexNo)+"','"+(pageRoman)+"','"+(pageArabic)+"','"+(illustration)+"','"+(size)+"','"+(otherAuthurs)+"'"
+ "'"+(addedEntries)+"','"+(lengthOfBook)+"','"+(accessionNo)+"','"+(calNo1)+"','"+(calNo2)+"','"+(calNo3)+"','"+(calNo4)+"')";
i have tried so many solutions even from stacflowoverflow there seem to no solution thanks for your help.
You need trailing commas on the fields at the end of the rows. Try this:
String sql = "insert into cataloguetb(title_statement,aurthurs_name,edition_statement,book_title,publisher_name,"
+ "place_of_publication,year_of_publication,isbn_no,index_no,pagenRomannuem,pagneArabi,illuss,size_of_book,"
+ "otherAurthurs,addEntries,length_in_cm,accessionNO,call_No1,call_No2,call_No,call_No4) values ('"+(titleStatement)+ "','"+(aurthursName)+"',"
+ "'"+(editionStatement)+"','"+(bookTitle)+"','"+(publisherName)+"','"+(placeOfPublication)+"','"+(yearOfPublication)+"',"
+ "'"+(isbnNo)+"','"+(indexNo)+"','"+(pageRoman)+"','"+(pageArabic)+"','"+(illustration)+"','"+(size)+"','"+(otherAuthurs)+"',"
+ "'"+(addedEntries)+"','"+(lengthOfBook)+"','"+(accessionNo)+"','"+(calNo1)+"','"+(calNo2)+"','"+(calNo3)+"','"+(calNo4)+"')";
This is because number of columns that you want to enter and datas(values for columns) you are entering are not same
the output of your code will be something like this
insert into cataloguetb(title_statement,aurthurs_name,edition_statement,book_title,publisher_nameplace_of_publication,year_of_publication,isbn_no,index_no,pagenRomannuem,pagneArabi,illuss,size_of_bookotherAurthurs,addEntries,length_in_cm,accessionNO,call_No1,call_No2,call_No,call_No4)values (.......)
That means you trying to insert in 19 columns but giving 21 values.So the error.
Well it is not the proper way of insertion.
Better would be to use PreparedStatement like this way
PreparedStatement pt=con.prepareStatement("insert into table (x,y) values(?,?");
pt.setString(1,value_for_x);
pt.setString(2,value_for_y);
pt.executeUpdate();

keep column name variable in Java INSERT INTO command with PreparedStatement?

I have the following problem:
I have two tables in one data base which consist of the same columns besides the name of the last column. I want to write data into them using Java.
I want to use the same preparedStatement for both tables, where I check with an if-command whether it is table1 or table2. table2 has amount10 as the name for the last column, table1 has amount20 for it. This number is stored in a variable within my code.
Below you can see a (simplified) example and how I tried to let the column name variable but it doesn't work. Is there any way to fix this without copying the whole statement and manually changing the number variable?
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount`+"number") VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount`+"number" = ? ; ";
PreparedStatement insertDataStmt;
This will not work since variables number and table are not going to be magically injected into your insertData string while you are changing them.
I'd to a method prepareInsertstatement(String table, String number) that would return correct PreparedStatement:
public void prepareInsertStatement(Connection conn, Strint table, String number) {
String insertData = "INSERT INTO `database`.`"+table+"`
(`person_id`,`Date`,`amount+"number"') VALUES "+
"(?,?,?) ON DUPLICATE KEY UPDATE " +
"`person_id` = ? , " +
"`Date` = ? , " +
"`amount+"number"' = ? ; ";
PreparedStatement insertDataStmt = conn.prepareStatement(insertData);
return insertDataStmt;
}
Just remember to close the PreparesStatement when you don't need it any more.
I suppose that reason for that is invalid syntax. When you concatenate string for last column name you use code 'amount' + number. If your number value is 20, than concat result will be
'amount'20 that cause invalid syntax exception. Just move one extra ' after number.
"'amount" + number + "'"
Note: log, or just error that appears during this statement execution would be very useful to find right answer for your question.

Categories

Resources