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.
Related
I'm using JDBC in eclipse IDE , i want to put two foreign keys in my table 3 , one is referencing to the primary key in table 1 and one is referencing to the primary key in table 2. When i only put one foreign key constrains for any referencing table1 or table 2 , it works fine but when i include two it gives me sql exception as stated below:
java.sql.SQLSyntaxErrorException: 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 'foreign key(T2) references
Table2(T2) )' at line 1
String createString =
// TABLE 1
"CREATE TABLE " + this.tableName + " ( " +
"T1 varchar(50) NOT NULL PRIMARY KEY )";
// TABLE 2
"CREATE TABLE " + this.tableName + " ( " +`enter code here`
"T2 varchar(50) NOT NULL PRIMARY KEY )";
// TABLE 3
"CREATE TABLE " + this.tableName + " ( " +
"T1 varchar(50) " +
"T2 varchar(50) " +
"foreign key(T1) references Table1 (T1)" +
"foreign key(T2) references Table2(T2) )";
First, this is actually a MySQL question, unrelated to Java/JDBC. Secondly, and more importantly, you don't appear to be using the correct syntax, which would be...
CREATE TABLE TableName (
T1 varchar(50),
T2 varchar(50),
foreign key(T1) references Table1(T1),
foreign key(T2) references Table2(T2)
);
Formatted for your code, it would look like this:
String createString = "CREATE TABLE " + this.tableName + " ( " +
" T1 varchar(50)," +
" T2 varchar(50)," +
" foreign key(T1) references Table1(T1)," +
" foreign key(T2) references Table2(T2));";
You were missing commas after each item in the items list for your CREATE TABLE statement.
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.
what is the mysql problem ??
I do not know what the error is since I had not used foreign keys before
String clientes = "CREATE TABLE clientes("+
"ID INTEGER NOT NULL AUTO_INCREMENT,"+
"CUENTA INTEGER,"+
"NOMBRE VARCHAR(255),"+
"EDAD INTEGER,"+
"ADICIONAL INTEGER,"+
"DOMICILIO VARCHAR(255),"+
"PRIMARY KEY(ID))";
String cuenta = "CREATE TABLE cuenta("+
"CUENTA INTEGER,"+
"SALDOAFAVOR DOUBLE(14,2),"+
"SALDOENCONTRA DOUBLE(14,2),"+
"FECHACORTE DATE,"+
"LIMITECREDITO DOUBLE(14,2),"+
"FOREIGN KEY(CUENTA) REFERENCES clientes(CUENTA))";
The correct reference and definition would use the primary key:
CREATE TABLE cuenta (
CUENTA INTEGER AUTO_INCREMENT PRIMARY KEY,
CLIENTE_ID INT,
SALDOAFAVOR NUMERIC(14, 2),
SALDOENCONTRA NUMERIC(14, 2),
FECHACORTE DATE,
LIMITECREDITO NUMERIC(14,2),
FOREIGN KEY(CLIENT_ID) REFERENCES clientes(ID)
);
Notes:
CUENTA seems like it should be the primary key of this table.
The foreign key reference should use the id on CLIENTES.
You don't need CUENTA on CLIENTES.
DOUBLE(14, 2) is not the right data type. You want DECIMAL(14, 2)/NUMERIC(14, 2).
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.
The first 2 go through without a hitch, but when I try to do the last one, I get this error message:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (corejava., CONSTRAINT #sql-8b8_50_ibfk_2 FOREIGN KEY (call_Number) REFERENCES book (call_Number))
There has got to be a way around this right?
Please see corrected code below: For any other newbies out there, my transaction call_Number INSERT field had incorrect values (tiny, minor, incorrect values!!!!)
s.executeUpdate (
"CREATE TABLE transaction ("
+ "patron_ID CHAR(10) NOT NULL,"
+ "call_Number CHAR(10) NOT NULL, check_Out_Date DATE NOT NULL, check_In_Date DATE NOT NULL,"
+ "PRIMARY KEY (patron_ID, call_Number),"
+ "overdue CHAR(15), total_Charge FLOAT)");
count3 = s.executeUpdate (
"INSERT INTO transaction"
+ " VALUES"
+ "('P222200000','MY.111.000','2011-06-06','2011-06-12','yes',5.00),"
+ "('P222200001','MY.111.001','2011-07-06','2011-07-12','no',5.00),"
+ "('P222200002','SF.111.002','2011-08-06','2011-08-12','yes',5.00),"
+ "('P222200003','SF.111.003','2011-09-06','2011-09-12','no',5.00),"
+ "('P222200004','AV.111.004','2011-10-06','2011-10-12','yes',5.00),"
+ "('P222200005','AV.111.005','2011-11-06','2011-11-12','no',5.00),"
+ "('P222200006','CO.111.006','2011-12-06','2011-12-12','yes',5.00),"
+ "('P222200007','CO.111.007','2011-01-06','2011-01-12','no',5.00),"
+ "('P222200008','IN.111.008','2011-02-06','2011-02-12','yes',5.00),"
s.executeUpdate(
"ALTER TABLE transaction ADD FOREIGN KEY (patron_ID) references " + dbName + ".patron (patron_ID)");
s.executeUpdate (
"ALTER TABLE patron ADD FOREIGN KEY (call_Number) references " + dbName + ".book (call_Number)");
s.executeUpdate (
"ALTER TABLE transaction ADD FOREIGN KEY (call_Number) references " + dbName + ".book (call_Number)");