Error with foreign key - java

I'm having problems with creating mySQL table within Java program. I constantly get Can't create table... errno: 150
Here is my code:
String URL="jdbc:mysql://192.168.1.128:3306";
Connection con=(Connection) DriverManager.getConnection(URL,user,pass);
Statement stmt=(Statement) con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
Statement stmt1=(Statement) con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String mySQL_new_table=("CREATE TABLE IF NOT EXISTS dbtest.T_AJPES_TR " + "(" + "row_count INT PRIMARY KEY AUTO_INCREMENT,"
+ "rn CHAR(15),sSpre CHAR(5),reg CHAR(5),eno VARCHAR(10),davcna VARCHAR(15),Ime VARCHAR(75),Priimek VARCHAR(75),LOG_ID INT,INDEX L_ID (LOG_ID),FOREIGN KEY(LOG_ID) references T_AJPES_TR_LOG(ID_LOG) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE = INNODB;");
String mySQL_log = ("CREATE TABLE IF NOT EXISTS dbtest.T_AJPES_TR_LOG" + "(ID_LOG INT PRIMARY KEY AUTO_INCREMENT, Date_import VARCHAR(45),File_import VARCHAR(75)) ENGINE = INNODB;");
stmt.executeUpdate(mySQL_new_table);
stmt1.executeUpdate(mySQL_log);
ResultSet uprs=stmt.executeQuery("SELECT * FROM dbtest.T_AJPES_TR");
ResultSet uprs1=stmt1.executeQuery("SELECT * FROM dbtest.T_AJPES_TR_LOG");
I googled many tutorials for creating foreign key and I still have problems. So what I'm doing wrong?

You've likely got an issue with foreign key constraints, see http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html for more details.
First one to check is whether your LOG_ID reference to T_AJPES_TR_LOG(ID_LOG) is correct

Related

Can't add foreign key constraints in sqlite using java

My table is :
Statement s5 = conn.createStatement();
ResultSet res5 = s5.executeQuery("Select name from sqlite_master where type = 'table' and name = 'actor_director'");
if(!res5.next()){
Statement ad = conn.createStatement();
ad.executeUpdate("create table actor_director(actor_ID integer, director_ID integer,"
+ "foreign key(actor_ID) references actor(actor_ID) ON UPDATE CASCADE ON DELETE CASCADE,"
+ "foreign key(director_ID) references director(director_ID)) ON UPDATE CASCADE ON DELETE CASCADE");
}
and i also did :
public static Connection getConnection() throws SQLException{
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
conn = DriverManager.getConnection("jdbc:sqlite:movieandtvseries.db", config.toProperties());
return conn;
}
When i run the program i get this error :
SQLiteException: [SQLITE_ERROR] SQL error or missing database (near "ON": syntax error)
You seem to have a typo in the line:
+ "foreign key(director_ID) references director(director_ID)) ON UPDATE CASCADE ON DELETE CASCADE");
There is an extra ')' after 'director_ID'. There is also a ')' missing after the last 'CASCADE' and before the double quote.

Can you add more than one table at a time with stmt.executeUpdate)

I am trying to add a second table to a H2 database using stmt.executeUpdate. The code already creates a table, but when i tried to duplicate the statement to create another(different name ofcourse) it didnt work. Then i started thinking if you could create two tables at a time with only one stmt.execute. Is this possible?
Code as follows:
private Statement getStatement(Connection con) throws SQLException {
Statement stmt = con.createStatement();
// stmt.executeUpdate("DROP TABLE e_mail");
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS e_mail ( source_url varchar(255), e_mail varchar(255), UNIQUE KEY (e_mail) )");
stmt.executeUpdate("CREATE TABLE IF NOT EXISTS urls_visited ( source_url varchar(255), urls_visited varchar(255), UNIQUE KEY (source_url) )");
return stmt;

How to get foreign key reference with Derby JDBC?

I have tables created with
CREATE TABLE COUNTRY (NAME CHAR(16) PRIMARY KEY)
CREATE TABLE PERSON (NAME CAHR(32) PRIMARY KEY,
CITIZENSHIP CHAR(16) CONSTRAINT CY_FK REFERENCES COUNTRY (NAME))
So how can I get Table.Column (COUNTRY.NAME) reference of the foreign key after I've performed SELECT query on PERSON table?
Is it possible to do via JDBC ResultSet, ResultSetMetaData or something alike?
In fact, I need to know:
either column has a Foreign Key constraint;
list of constraint values.
Well, I did SELECT on SYS.SYSCONSTRAINTS but there are only types of constraints ('P', 'F', etc) but no Referenced Tables' names.
Update
I send queries to the Database via JDBC
PreparedStatement stmtDerbyDb = DriverManager.getConnection(dbConnectString).prepareStatement("SELECT * FROM \"" + dbTableOrView + "\"");
ResultSet rsltDerbyDb = stmtDerbyDb.executeQuery();
ResultSetMetaData rsmdDerbyDb = rsltDerbyDb.getMetaData();
...
All the variables stmtDerbyDb, rsltDerbyDb, rsmdDerbyDb are used in further code. I need to know: is it possible to fetch Foreign Key constraints from dbTableOrView via JDBC or shall I query SYS.* system tables somehow?
Possible decision:
...
Connection connTableView = DriverManager.getConnection("jdbc:Derby:database_name:create=false");
DatabaseMetaData dbmdTableView = connTableView.getMetaData();
ResultSet rsltTableConstraints = dbmdTableView.getImportedKeys(null, null, "PERSON");
PreparedStatement prstTableContents = connTableView.prepareStatement("SELECT * FROM PERSON");
ResultSet rsltTableContents = prstTableContents.executeQuery();
...
buildTableView(rsltTableContents);
rsltTableContents.close();
...
while (rsltTableConstraints.next()) {
PreparedStatement prstConstraints = connTableView.prepareStatement("SELECT " + rsltTableConstraints.getString("PKCOLUMN_NAME") + " FROM " + rsltTableConstraints.getString("PKTABLE_NAME"));
ResultSet rsltConstraintsForCol = prstConstraints.execute();
...
setColumnConstraints(rsltConstraintsForCol, rsltTableConstraints.getString("FKCOLUMN_NAME"));
...
rsltConstraintForCol.close();
prstConstraints.close();
}
...
Which is supposed to be used as ComboBox dropdowns with constraints per column (with FK of course).

Preventing from Multiple primary key error

This is my code for executing in my java program:
public static void createBooksTablesAndSetPK() {
String selectDB = "Use lib8";
String createBooksTable = "Create table IF NOT EXISTS books (ID int,Name varchar(20),ISBN varchar(10),Date date )";
String bookTablePK = "ALTER TABLE BOOKS ADD PRIMARY KEY(id)";
Statement st = null;
try (
Connection con = DriverManager.getConnection(dbUrl, "root", "2323");) {
st = con.createStatement();
st.execute(selectDB);
st.execute(createBooksTable);
st.execute(bookTablePK);
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
I cat use IF NOT EXIST for creating databasesand tables to prevent creating duplicate database and tables and corresponding errors.
But i don't know how prevent Multiple primary key error, because program may call createBooksTablesAndSetPK() multiple times.
Error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Multiple primary key defined
The column Book_id is not existing in your case. You are creating a table with ID as the column and then updating the table with a PRIMARY KEY constraint on a column that is not existing.
Create table IF NOT EXISTS books (ID int,Name varchar(20),ISBN varchar(10),Date date )
ALTER TABLE BOOKS ADD PRIMARY KEY(BOOK_id)
Try running these statements on a MySQL command prompt (or MySql Workbench) and the see the error.
You need change the alter table command like this.
ALTER TABLE BOOKS ADD BOOK_id VARCHAR( 255 ), ADD PRIMARY KEY(BOOK_id);

MySQLSyntaxErrorException when creating table

I am fairly new to MySQL with Java, but I have executed a few successful INSERT queries however cannot seem to get the CREATE TABLE query to execute without getting the MySQLSyntaxErrorException exception. My code is as follows:
Statement stmt;
String url = "jdbc:mysql://localhost:3306/mysql";
Connection con = DriverManager.getConnection(url, "root", "password");
stmt = con.createStatement();
String tblSQL = "CREATE TABLE IF NOT EXISTS \'dev\'.\'testTable\' (\n"
+ " \'id\' int(11) NOT NULL AUTO_INCREMENT,\n"
+ " \'date\' smallint(6) NOT NULL\n"
+ ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
stmt.executeUpdate(tblSQL);
stmt.close();
con.close();
And the error is as follows:
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 ''dev'.'testTable' (
'id' int(11) NOT NULL AUTO_INCREMENT,
'date' smallint(6) N' at line 1
I would appreciate it if anyone could spot the mistake in this query, as I've tried executing this within phpMyAdmin and it works as it should.
\n will make press enter effect :) make it like
String tblSQL = "CREATE TABLE IF NOT EXISTS `dev`.`testTable`"
+ "("
+ "id INTEGER(11) NOT NULL AUTO_INCREMENT primary key,"
+ "date smallint(6) NOT NULL"
+ ")"
+ "ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";

Categories