Preventing from Multiple primary key error - java

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);

Related

java + SQLite project. Foreign key "On Update" not updating

I am making a javafx (intelliJ with java jdk 11) app using SQLite version 3.30.1 with DB Browser for SQLite.
I have a table called "beehives" and each beehive can have diseases (stored in the table "diseases").
this is my "beehives" table:
CREATE TABLE "beehives" (
"number" INTEGER NOT NULL,
"id_apiary" INTEGER NOT NULL DEFAULT -2,
"date" DATE,
"type" TEXT,
"favorite" BOOLEAN DEFAULT 'false',
PRIMARY KEY("number","id_apiary"),
FOREIGN KEY("id_apiary") REFERENCES "apiaries"("id") ON DELETE SET NULL
);
this is my "diseases" table:
CREATE TABLE "diseases" (
"id" INTEGER NOT NULL,
"id_beehive" INTEGER NOT NULL,
"id_apiary" INTEGER NOT NULL,
"disease" TEXT NOT NULL,
"treatment" TEXT NOT NULL,
"start_treat_date" DATE NOT NULL,
"end_treat_date" DATE,
PRIMARY KEY("id"),
FOREIGN KEY("id_beehive","id_apiary") REFERENCES "beehives"("number","id_apiary") ON UPDATE CASCADE
);
this is my "apiaries" table in case you need it:
CREATE TABLE "apiaries" (
"id" INTEGER NOT NULL,
"name" TEXT NOT NULL,
"address" TEXT,
PRIMARY KEY("id")
);
Everything works fine, but when I update a beehive (for example when I update the "number", which is the primary key in beehives table) the diseases does not update the number. The result is that the diseases get some kind of disconnected since the beehive change his "number" correctly, but the disease doesn't update it. There is no error message.
My java method that calls the update is:
public void updateBeehiveInDB(Beehives newBeehive,Beehives oldBeehive){
try {
s = "UPDATE beehives SET number=?, id_apiary=?, date=?, type=?, favorite=? WHERE number=? and id_apiary=? ";
preparedStatement = connection.prepareStatement(s);
preparedStatement.setInt(1, newBeehive.getNumber());
preparedStatement.setInt(2, newBeehive.getId_apiary());
preparedStatement.setDate(3, newBeehive.getDate());
preparedStatement.setString(4, newBeehive.getType());
preparedStatement.setBoolean(5, newBeehive.isFavorite());
preparedStatement.setInt(6, oldBeehive.getNumber());
preparedStatement.setInt(7,oldBeehive.getId_apiary());
int i = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
I tried to check if foreign keys are "on" following the SQLite documentation here, but my English is not good enough and I am using DB Manager. So no idea how to check if this is on, or how to turn it on manually.
What can I do to update the diseases "id_beehives" when I update "number" on beehives table?
The problem was that i am using a composite foreign key and i need to implement it correctly on other tables too even if i was not using them yet in this new project. Was very hard to find the problem because intellij normally show all the SQL error messages, but in this case, it was not showing anything. But when i tried to do the SQL sentence manually in the DB Browser, there i got an error message and was able to fix it.
Also had to activate foreign key on the connection:
public Connection openConnection() {
try {
String dbPath = "jdbc:sqlite:resources/db/datab.db";
Class.forName("org.sqlite.JDBC");
SQLiteConfig config = new SQLiteConfig();
config.enforceForeignKeys(true);
connection = DriverManager.getConnection(dbPath,config.toProperties());
return connection;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

java.lang.UnsupportedOperationException: DROP CONSTRAINT is only supported for Hibernate

I am trying to drop a foreign key constraint in a table but the SQL "DROP CONSTRAINT" Statement is not supported by ucanaccess. the error says:
java.lang.UnsupportedOperationException: DROP CONSTRAINT is only supported for Hibernate hbm2ddl.auto "create"
Does anybody know a way around this?
private void dropTables() throws SQLException {
final String RENTALS = "RENTALS";
Statement statement = conn.createStatement();
DatabaseMetaData metaData = conn.getMetaData();
ResultSet rs = metaData.getTables(null, null, RENTALS, null);
while (rs.next()) {
if (rs.getString(3).equals(RENTALS)) {
statement.executeUpdate("ALTER TABLE RENTALS DROP CONSTRAINT"
+ " custNumber;");
statement.executeUpdate("ALTER TABLE RENTALS DROP CONSTRAINT"
+ " vehNumber;");
statement.executeUpdate("DROP TABLE CUSTOMERS;");
statement.executeUpdate("DROP TABLE VEHICLE;");
statement.executeUpdate("DROP TABLE RENTALS;");
}
}
}
The error message implies that setting hbm2ddl.auto to create would solve the problem:
<entry key="hibernate.hbm2ddl.auto" value="create">
However, you might want to think twice before doing this, as this means that all the tables associated with your Hibernate entities will be created and dropped each time you start the application.

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 super table information in java?

My database had a lot of parent and child tables.The tables contains the foreign key which has the link with the parent table.I wants to get the information of parent table of the child table using java?How can I achieve that?
For ex,consider the student and mark table,
The student table contains the information like studentID,name.
studentID-Primary key
The marks table contains the markId,studentId,Sub1,sub2,sub3 etc
markId-Primarykey
studentID-Foreignkey refers Student table
My table creation queries are,
CREATE TABLE `Student12` (
`studentId` SMALLINT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`studentId`)
)
ENGINE = InnoDB;
CREATE TABLE `Marks` (
`markId` SMALLINT NOT NULL AUTO_INCREMENT,
`subject1` SMALLINT NOT NULL,
`subject2` SMALLINT NOT NULL,
`studentId` SMALLINT NOT NULL,
PRIMARY KEY (`markId`),
CONSTRAINT `FK_Marks_Student` FOREIGN KEY `FK_Marks_Student` (`studentId`)
REFERENCES `Student12` (`studentId`)
ON DELETE RESTRICT
ON UPDATE RESTRICT
)
ENGINE = InnoDB;
If I give the mark table name as input, how can I get its parent or super table name student and information about student table?Any help should be appreciable.
It totally depends on the way tables are created. Foreign keys are not mandatory to create, they could be a simple column in one table with no explicit relationship to the other table. If you are very sure that the links are created explicitly (the foreign keys are defined) then you could use information_schema. But if there is no foreign key defined (which is true in most of the databases I have seen), then there is no way for you to find the links inside the database. You have to look into the code (if there is any available) and try to find a clue.
The JDBC DatasetMetaData interface provides a couple of methods that may help. (The following text is copied from the javadoc.
ResultSet getExportedKeys(String catalog, String schema, String table)
Retrieves a description of the foreign key columns that reference the given table's primary key columns (the foreign keys exported by a table).
ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable)
Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key or the columns representing a unique constraint of the parent table (could be the same or a different table).
Of course, these can only work if the relevant columns have been declared as foreign keys in the SQL table DDL.
You can use the DatabaseMetaData to retrieve informations about foreign keyes
and the referenced Tables. Im not sure if it works with all kinds of MySql Tables.
The principle is to use the follwing code (not tested) to retrieve information about the super tables
ResultSet rs = null;
DatabaseMetaData dm = conn.getMetaData( );
// get super tables of table marks
ResultSet rs = dm.getSuperTables( null , null, "marks" );
while( rs.next( ) ) {
System.out.println(String.format("Table Catalog %s", rs.getString("TABLE_CAT") );
System.out.println(String.format("Table Schema %s", rs.getString("TABLE_SCHEM") );
System.out.println(String.format("Table Name %s", rs.getString("TABLE_NAME") );
System.out.println(String.format("Table Name %s", rs.getString("SUPERTABLE_NAME") );
}
You can use thes informations to get additional informations about the referenced table
and the foreigen and referenced primary keys:
ResultSet rs = dm.getCrossReference( null , null , "student" , null , null , "marks" );
System.out.println(String.format("Exported Keys Info Table %s.", "marks"));
while( rs.next( ) ) {
String pkey = rs.getString("PKCOLUMN_NAME");
String ptab = rs.getString("PKTABLE_NAME");
String fkey = rs.getString("FKCOLUMN_NAME");
String ftab = rs.getString("FKTABLE_NAME");
System.out.println("primary key table = " + ptab);
System.out.println("primary key = " + pkey);
System.out.println("foreign key table = " + ftab);
System.out.println("foreign key = " + fkey);
}
And finally you can retrieve the information about the super table by
ResultSet rs = dm.getTables(null,null,"student" ,null);
System.out.println("Table name:");
while (rs.next()){
String table = rs.getString("TABLE_NAME");
System.out.println(table);
}

Error with foreign key

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

Categories