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.
Related
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.
I am creating a bus table with an event to maintain th data. Is it possible to drop the table and the autoDelete event by DropBusEvent event if no records exist in the bus table?
stt.execute("CREATE TABLE IF NOT EXISTS bus"
+ "(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,"
+ "mac VARCHAR(30) NOT NULL UNIQUE,"
+ "route int(11) NOT NULL,"
+ "latitude FLOAT(10,6) NOT NULL,"
+ "longitude FLOAT(10,6) NOT NULL,"
+ "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
stt.execute("CREATE EVENT IF NOT EXISTS AutoDelete "
+ "ON SCHEDULE EVERY 3 MINUTE "
+ "DO "
+ "DELETE FROM bus WHERE created_at < (NOW() - INTERVAL 3 MINUTE)");
// I tried this statement here but it does not work.
stt.execute("CREATE EVENT IF NOT EXITS DropBusTable "
+ "Do "
+ "DROP TABLES IF EXISTS bus");
I am getting 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 'EXITS DropBusTableDROP TABLES IF EXISTS bus' at line 1
You have a mistake in your syntax:
EXITS instead of EXISTS
in the line
stt.execute("CREATE EVENT IF NOT EXITS DropBusTable "
I am trying to insert data into arrivaltimes tables but I am getting the following error:
java.sql.SQLException: Field 'id' doesn't have a default value
stt.execute("CREATE TABLE IF NOT EXISTS stops"
+ "(stop_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, "
+ " name varchar(30) NOT NULL, "
+ " route INT(11) NOT NULL, "
+ " lat double(10,6) NOT NULL, "
+ " longi double(10,6)NOT NULL) " );
stt.execute("INSERT INTO stops(name, route, lat, longi) values"
+ "('blabla', '1', '93.838039', '15.700440' ),"
+ "('backery', '9', '98.868863', '19.665438' )" );
stt.execute("CREATE TABLE IF NOT EXISTS arrivaltimes(id INT(11) NOT NULL PRIMARY KEY,"
+ " weekday VARCHAR(20) NOT NULL,"
+ "arrivaltime time NOT NULL,"
+ " stop_id INT, FOREIGN KEY fk_stop_id(stop_id) REFERENCES stops(stop_id) )" );
//The error appears in this execution statement.
stt.execute("INSERT INTO arrivaltimes(weekday, arrivaltime) values"
+ "('mon-fri', '05:30' ),"
+ "('mon-fri', '06:07' )" );
You are missing AUTO INCREMENT for Primary Key in arrivaltimes table. Just need to add AUTO_INCREMENT while creating table
stt.execute("CREATE TABLE IF NOT EXISTS arrivaltimes(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,"
+ " weekday VARCHAR(20) NOT NULL,"
+ "arrivaltime time NOT NULL,"
+ " stop_id INT, FOREIGN KEY fk_stop_id(stop_id) REFERENCES stops(stop_id) )" );
Because the column id is defined as NOT NULL which means it has to have a value and you're not providing one.
I was having the same problem with my table in MySQL WorkBench. Clearly, it is the auto increment command that is giving the Field 'id' a default value. Here is the code that worked for my table:
create table product( <br>
id int auto_increment PRIMARY KEY, <br>
name varchar(20), <br>
description varchar(100), <br>
price decimal(8,3) <br>
);
I am trying to make a variable Table name through Java.
My code is :
public void createTable(String tableName){
try {
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE '"+tableName+"'" +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
}
catch (SQLException e){
e.printStackTrace();
}
}
It gives me a syntax error saying:
Incorrect syntax near 'VariableTableNameIChose'.
Does anyone have any ideas?
It could be one of 2 things or the combination of both.
Maybe the single quotes around the table name are not valid in your database. So do like this:
stmt.executeUpdate("CREATE TABLE "+tableName+" " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
Or maybe you need a spaces between the table name and the ( following after:
Statement stmt = con.createStatement();
// v this one was missing
stmt.executeUpdate("CREATE TABLE '"+tableName+"' " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
The table name is an identifier. Identifiers do not use single quotes (in standard SQL).
"CREATE TABLE '"+tableName+"' "
Will result in
CREATE TABLE 'foobar'
which is invalid SQL. You need to remove the single quotes:
"CREATE TABLE "+tableName+" " + ...
As the table name is apparently a user input, you might actually want to use quoted identifiers (although this is in general a bad idea). Identifiers are quoted using double quotes in the SQL standard:
"CREATE TABLE \""+tableName+"\" " + ...
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)");