How might I fix my java databasing error? - java

I've narrowed down my problem to these lines of code and I know it has something to do with the syntax. The error i get is: [Microsoft][ODBC Microsoft Access Driver] Syntax error in field definition the section of code I get the error from is:
try {
System.out.println("Creating StockTrades table...");
stmt.executeUpdate("CREATE TABLE StockTrades (userID TEXT(20) CONSTRAINT FK1_StockTrades REFERENCES "
+ "Users (userID), symbol TEXT(8), CONSTRAINT FK2_StockTrades FOREIGN KEY (symbol) "
+ "REFERENCES Stocks (symbol), numStocks INT, pricePerStock DECIMAL(5, 2), "
+ "stocksPurchased INT, stocksSold INT, totalCashPaid DECIMAL(9, 2), "
+ "totalCashReceived DECIMAL(9, 2))");
} catch(Exception ex) {
System.out.println("Exception creating StockTrades table: " + ex.getMessage());
}
try {
System.out.println("Creating StockTrades table primary key index...");
stmt.executeUpdate("CREATE UNIQUE INDEX PK_StockTrades ON StockTrades (userID, symbol) "
+ "WITH PRIMARY DISALLOW NULL");
} catch(Exception ex) {
System.out.println("Exception creating StockTrades index: " + ex.getMessage());
}

Solution: To save people from reading through all the comments, this issue was solved by switching from a Decimal field type to the Currency type. The underlying issue was never identified or solved for those who can't switch away from the decimal type.
If I were to guess, I'd say it's this line:
symbol TEXT(8), CONSTRAINT FK2_StockTrades FOREIGN KEY
It seems you have an extra comma between text(8) and the constraint.
Edit: I had posted this just before the other poster then voted to delete. After researching it, you can do it either way, with or without the comma. However, you have it done both ways in consecutive lines. Perhaps that's the issue?

CREATE TABLE StockTrades (userID TEXT(20) CONSTRAINT FK1_
^---
missing comma?

Related

How to declare foreign keys in Apache Derby?

I am trying to make a R.D.B. at the moment, but I can't seem to get the foreign keys working. When running the program, the two tables without foreign keys (Words and PDFs) are created and then it has a run-time error at the Index table:
Table 'INDEX' contains a constraint definition with column 'WORDID' which is not in the table. Derby shut down normally
Here is my code:
new String createSQL3 = "create table Index ("
+ " IndexID integer not null generated always as"
+ " identity (start with 1, increment by 1),"
+ " IndexPage integer not null, IndexOccurences integer not null,"
+ " constraint IndexID_PK primary key (IndexID),"
+ " constraint WordID_FK FOREIGN KEY (WordID) REFERENCES Words(WordID),"
+ " constraint PDFID_FK FOREIGN KEY (PDFID) REFERENCES PDFs(PDFID))";
statement.execute(createSQL3);
System.out.println("Table Index created successfully");
connection.commit();
} catch (SQLException EX) {
System.out.println(EX.getMessage());
This syntax:
constraint WordID_FK FOREIGN KEY (WordID) REFERENCES Words(WordID)
says that you want the column WordID in the table Index to be a reference to the column WordID in the table Words.
But you did not define a column named WordID in the table Index, as the message says. Your Index table has only three columns: IndexID, IndexPage, and IndexOccurrences.
You probably want to have something like
WordID integer,
in your definition of table Index.

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.

How can I create a Table with two Foreign Key References to one other Table via UCanAccess?

To build the References direct in MS-Access is no Problem.
To do it with UCanAccess results in a "net.ucanaccess.jdbc.UcanaccessSQLException:...".
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection connection = DriverManager.getConnection("jdbc:ucanaccess://e:/TestDB.accdb;memory=true");
Statement statement = connection.createStatement();
//
String tableToBeReferenced = "PersonsTable";
String tableWithTheReferences = "RelationShipsTable";
try {// Tidy up
statement.execute("DROP TABLE " + tableWithTheReferences);
} catch (Exception exeption) {}
try {// Tidy up
statement.execute("DROP TABLE " + tableToBeReferenced);
} catch (Exception exeption) {}
statement.execute("CREATE TABLE " + tableToBeReferenced + "(ID autoincrement NOT NULL PRIMARY KEY,"//
+ "Name VARCHAR(255)"//
+ ")");
statement.execute("CREATE TABLE " + tableWithTheReferences + "(ID LONG NOT NULL PRIMARY KEY,"//
+ "RelationShip VARCHAR(255) NOT NULL DEFAULT 'FRIENDS',"//
+ "Person1Id LONG NOT NULL,"//
+ "Person2Id LONG NOT NULL)");
// reference #1
statement.execute("ALTER TABLE " + tableWithTheReferences + //
" ADD CONSTRAINT FOREIGN_KEY_1 FOREIGN KEY (Person1Id) REFERENCES " //
+ tableToBeReferenced + "(ID) ON DELETE CASCADE");
// reference #2
statement.execute("ALTER TABLE " + tableWithTheReferences + //
" ADD CONSTRAINT FOREIGN_KEY_2 FOREIGN KEY (Person2Id) REFERENCES " //
+ tableToBeReferenced + "(ID) ON DELETE CASCADE");
If I create only the first Reference it works.
If I create only the second Reference it works.
But when I try to build both References it fails.
I am able to reproduce the issue under UCanAccess 4.0.3. Neither HSQLDB nor Jackcess has a problem with creating two independent FK relationships between the same two tables, so it looks like it might be a bug in UCanAccess. I will report the issue to the UCanAccess development team and update this answer with any news.
Update:
A fix for this issue has been implemented and will be included in the UCanAccess 4.0.4 release.
I think it will not work since you have "ON DELETE CASCADE" for both your foreign keys.

Database value insertion Error

How can i manually insert values if not exist...i tried following code but it produce error.How can i insert values if not exist in the table
String sql1 = "CREATE TABLE IF NOT EXISTS admin " +
"(id INTEGER not NULL AUTO_INCREMENT, " +
" user_name VARCHAR(255), " +
" password VARCHAR(255), " +
" isAdmin BOOLEAN NOT NULL DEFAULT '0', " +
" memo VARCHAR(255), " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql1);
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
stmt.executeUpdate(insert);
it produce an error like
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'mem' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
String insert="INSERT INTO admin IF NOT EXISTS(id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
should be
String insert="INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo)VALUES(1,'admin','admin',1,'memo')";
MySQL (and any other SQL implementation as well) doesn't support IF NOT EXISTS in INSERT queries.
your INSERT query must be
"INSERT IGNORE INTO admin (id,user_name,password,isAdmin,memo) VALUES (1,'admin','admin',1,'memo')"
What you want may be INSERT ... ON DUPLICATE KEY UPDATE or INSERT IGNORE....
The former will update an existing row if a duplicate insert is detected, while the latter will just throw away duplicate inserts.
In both cases, you'll have to create a UNIQUE constraint on the column you want to check for duplicates. If the UNIQUE is violated, the alternate function is invoked.

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException - Unknown column in field list

I am getting the following error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'userId' in 'field list'
The code which is causing this error is this:
PreparedStatement pstmt =
con.prepareStatement(
"INSERT INTO " +
tableName +
" (userId,username,email,password) VALUES (?,?,?,?)");
My table gets created by the following command
stmt.executeUpdate(
"CREATE TABLE " +
tableName +
" (" +
" userId INT, " +
" userName VARCHAR(255) NOT NULL, " +
" email VARCHAR(255) NOT NULL, " +
" password VARCHAR(255), " +
" PRIMARY KEY(userId)" +
" )");
stmt.close();
Can someone help me spot my mistakes if any. I am a novice in this so I am kind of struggling to find where exactly the error is.
The error was because there already existed another table with the same table name.
One other thing to look at is triggers. I was getting the same error and eventually determined that the error was the result of a trigger statement rather than the insert statement. The "unknown column" was in a table the trigger was trying to insert into.
If you are using insert statement and there is column value missing or empty. It can give this error. I was using prepared statement. I got this error for a column having numeric data type. The root cause of this was empty string being passed as column value. Strangely it throws "unknown column" e

Categories

Resources