executing sql constraints in JDBC code - java

So after creating tables using jdbc, I have this code to make one to many relationship between UserInfoTable and ContactTable and UserInfoID as foreign key.
String addConstraint = "alter table ContactTable"+
"ADD CONSTRAINT FK_ContactTable_UserInfoTable"+
"FOREIGN KEY(UserInfoID)"+
"REFERENCES UserInfoTable (UserInfoID)"+
"ON UPDATE CASCADE"+
"ON DELETE CASCADE";
But when I execute this,
con.prepareStatement(addConstraint).executeUpdate();
I'm getting
java.sql.SQLException: Incorrect syntax near the keyword 'CONSTRAINT'.
I'm really confused. I handcoded this query several times in sql server and I think my syntax is correct because it always executed successfully, why not when executed by java code?

You are concatenating strings but the different segments have no spaces, this could be causing keywords to be bunched together with your data creating invalid keywords.
It is simple but this may be all you need:
String addConstraint = "alter table ContactTable "+
"ADD CONSTRAINT FK_ContactTable_UserInfoTable "+
"FOREIGN KEY(UserInfoID) "+
"REFERENCES UserInfoTable (UserInfoID) "+
"ON UPDATE CASCADE "+
"ON DELETE CASCADE";

Related

Running IBM Db2 DDL statements in JDBC

I need to alter a Db2 column using JDBC. The column may change its name and/or its type. In Db2 these two actions are done in two steps, the first ALTER TABLE to change the name, and the second ALTER TABLE to change the type.
For example:
ALTER TABLE T1 RENAME COLUMN C1 TO C2;
ALTER TABLE T1 ALTER COLUMN C2 SET DATA TYPE decimal(4,0);
See below the code, the first statement is executed but the second always throws an exception.
String sql = "ALTER TABLE " + tableName + " RENAME COLUMN " +
originalName + " TO " + name;
PreparedStatement ps1 = conn.prepareStatement(sql);
ps1.executeUpdate();
sql = "ALTER TABLE " + tableName + " ALTER COLUMN " + name +
" SET DATA TYPE decimal(" + sc.getLength() + "," + sc.getDec() + ")";
PreparedStatement ps2 = conn.prepareStatement(sql);
ps2.executeUpdate();
The exception is:
The operation was not performed because the table is in an invalid
state for the operation. Table name: "DB.T1".
Reason code: "23".. SQLCODE=-20054, SQLSTATE=55019, DRIVER=4.27.25
What is the meaning of a table in an "invalid state"? Why is the table in this state? What's wrong with this code?
Always give your Db2-server platform (z/os, linux/unix/windows, i series) and Db2-server version when asking for Db2-help, because the answer can depend on these facts.
The exception SQL20054N reason 23, means that the table has reached a limit on the number of alterations and before continuing, the table need to be reorganized with a REORG command. The documentation for the error is here. The REORG command will put the table back into a normal state. Normally a DBA would consider running RUNSTATS command following the REORG to ensure that table statistics are refreshed following the alterations.
Db2-LUW allows a small number of table changes (often 3) before forcing a reorg for certain kinds of alterations. Previous alterations to this table might have been performed by others, in different transactions , without getting this exception. Schema-evolution tools should detect this state and recover from it.
This is a normal situation, and the recovery is to run the REORG command.
You can either ask your DBA to do reorg for you, or you can (if your authid has the correct permissions) from jdbc call a stored procedure admin_cmd() to perform the command for you, or just use the Db2 command line interface reorg table db.t1 inplace for example . The documentation for admin_cmd is here, and if you do not understand the REORG details, ask your DBA for help.

SQL: delete items from table based on their ID, which also appears in another table

long story short, I have a coupon system project.
in it I have companys, coupons and customer.
all of their data is save in an SQL DB, based on apache derby.
for example:
a company exist on the company table. has id, name, password, email
a coupon exist on the coupon table. has id, title, price, etc..
only a company can create a coupon, and what it does, not only it is created on the coupon table mentioned above, it is also populating a second 'index' table, joining company's and coupons= company_coupon. has company_id, coupon_id
now everything else in the project is working beautifully, and the tables are checked by my teachers and everything is configured correctly.
what I'm trying to do next, and just cant seem to figure out the syntax for is:
when I delete a company, I also want to delete every coupon this company has created, from the coupon table. this I do by searching the company_coupon table for company_id matches, and deleting based on the coupon_id paired with them.
I'm trying this statment:
String sql = "DELETE FROM coupon INNER JOIN company_coupon ON id = company_coupon.coupon_id WHERE company_coupon.company_id = "
sql += companyObject.getId();
<-- method is getting an object and I have access to it's id, but I tried hard coding a specific company id and still..
the same error keeps coming back in different variations:
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "INNER" at
line 1, column 8.
I searched online here and elsewhere, was advised to add an 'alias' after the DELETE. got the same error, pointing at that extra word:
"DELETE c FROM coupon INNER JOIN company_coupon ON id = company_coupon.coupon_id WHERE company_coupon.company_id = " ---->>
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "c" at
line 1, column 8.
any ideas? :(
You might need two delete statements:
delete from company where id=1;
delete from company_coupon where id_company=1;
If your database supports cascade deletes on foreign keys, you might need just one delete statement.
Take a look at: http://sqlfiddle.com/#!7/86102/6 (click "Run SQL" and scroll down to the bottom of the result, try changing the sql yourself)
Solved:
String sql = "DELETE FROM customer_coupon WHERE coupon_id IN (SELECT company_coupon.coupon_Id FROM company_coupon WHERE company_coupon.company_id = ";
sql += comp.getId();
sql += ")";

How to differentiate PrimaryKey and uniquekey Constraint in java

In both cases of PrimaryKey violation and uniqueKey violation, I see the same message, error code and sql state values.
When I run the insert query directly in the db, getting the same error message for both the cases. Only difference is the constraint name. we cannot rely on the constraint name all the time. How to differentiate the different types of SQL constraints violations?
try {
// create Db connection & sql insert into table statement
// stmt.executeUpdate("insert into mytable (A,B) .......")
// mytable has primary key on column A and unique key on column B
}catch(Exception e){
System.out.println(">>>>>>>>>> get Message :: " + e.getMessage());
System.out.println(">>>>>>>>>> get err code:: " + ((SQLException)e).getErrorCode());
System.out.println(">>>>>>>>>> get sql state:: " + ((SQLException)e).getSQLState());
}
Test 1:
>>>>>>>>>> get Message :: ORA-00001: unique constraint (TABLE_NAME.UK) violated
>>>>>>>>>> get err code:: 1
>>>>>>>>>> get sql state:: 23000
Test 2:
>>>>>>>>>> get Message :: ORA-00001: unique constraint (TABLE_NAME.PK) violated
>>>>>>>>>> get err code:: 1
>>>>>>>>>> get sql state:: 23000
we cannot rely on the constraint name all the time
And why ?
The constraint name has to be unique.
Consequently to distinguish programmatically from a SQLException a constraint violation from another one which both are the same constraint type and so have the same error code, you could check the constraint name.
If you don't want to use this way, you have to manually check that the data to insert doesn't violate the constraints set on the table.
It is also a way of proceeding but it will be more expensive to perform systematically a check before inserting.
If you know the constraint name and the schema owner, you can look up the constraint type from the all_constraints table.
For example:
select constraint_type from all constraints where owner='<your schema owner>'
and constraint_name = '<constraint name returned in your error>'
Look here for the various constraint type codes - https://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_1037.htm#i1576022
Given the name (PK or UK) can you find the meta data about that name?
For example, Oracle has the the ALL_CONSTRAINTS and ALL_INDEXES tables. ALL_CONSTRAINTShas a constraint_type column where P = primary key. ALL_INDEXES has a uniqueness column with values of UNIQUE or NONUNIQUE.
Hopefully your database has something similar.

UcanaccessSQLException: unexpected token: ORDER

I'm making a little app in Java and MySQL with PHPMyAdmin and all runs fine, but my professor says that we have to work with a database in Access, so I just changed my class connection and imported my database. The INSERT, SELECT and other UPDATE statements run fine but this statement just doesn't run.
UPDATE table SET col1=?, col2=? WHERE col0=? ORDER BY col4 DESC LIMIT 1
I can't understand how in MySQL it runs fine but with UCanAccess it doesn't work.
I can't understand how in MySQL it runs fine but with UCanAccess it doesn't work.
That's because the various producers of database software have taken it upon themselves to implement the SQL language in slightly different ways, so a given SQL statement written for MySQL is not guaranteed to work under Access, or Microsoft SQL Server, or Oracle, or any other "dialect" of SQL.
UCanAccess tries very hard to follow the Access SQL syntax. Access SQL uses TOP n instead of LIMIT n, but Access SQL also does not allow TOP n or ORDER BY in the main part of an UPDATE query. So you need to use a subquery to identify the primary key value of the row you want to update.
For example, if your table has a primary key column named "id" then you can do
sql =
"UPDATE table1 SET col1=?, col2=? " +
"WHERE id IN ( " +
"SELECT TOP 1 id " +
"FROM table1 " +
"WHERE col0=? " +
"ORDER BY col4 DESC, id " +
")";

Error executing Create table statement in Java?

I am trying to create 2 tables in MySql using Java JDBC,the first one runs fine but I get an error when I execute the second create table command. The problem looks like in the Foreign key definition not sure what's missing ?
Error :
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 'FOREIGN KEY(UniqueBusID)
REFERENCES BUS_3_CLEARBROOK_UFV_GOLINE_TO_UFV_BusDetai' at line 1
Code
String table_UniqueBusNameTimings = BusDetails+"_BusTimings";
String timings= "Timings";
String dayofweek = "DayOfWeek";
String FuniqueBusID = "UniqueBusID";
String table_UniqueBusNameDetails = BusDetails+"_BusDetails";
String PuniqueBusID = "UniqueBusID";
String StopNames = "StopNames" ;
String sql1 = "CREATE TABLE "+table_UniqueBusNameDetails+
"(UniqueBusID VARCHAR(255) not NULL, " +
" StopNames VARCHAR(1000), " +
" PRIMARY KEY ( UniqueBusID ))";
String sql2 = "CREATE TABLE "+table_UniqueBusNameTimings+
"(Timings VARCHAR(255) , " +
" DayOfWeek VARCHAR(25), " +
" UniqueBusID VARCHAR(255) "+
" FOREIGN KEY(UniqueBusID) REFERENCES "+table_UniqueBusNameDetails+"(UniqueBusID))";
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
You have a comma missing after UniqueBusID VARCHAR(255). Just change it to UniqueBusID VARCHAR(255), and your code shall be fine.
For details on syntax related to CREATE TABLE with FOREIGN KEY, you can explore this page: http://www.w3schools.com/sql/sql_foreignkey.asp
We should use CREATE TABLE IF NOT EXISTS... then if we are having foreign key relation then we should use SET FOREIGN_KEY_CHECKS=0; Finally we will execute a batch what having all the statement and then commit.
Every attribute like column, index, foreign key etc. should be seprated by comma ',' in table creation syntax. so here a comma missing after UniqueBusID VARCHAR(255). It will be fine after adding comma here.
#Suzon: We should not set foreign_key_checks=0 specially during creating table or adding any constraint at it will skip any constraint checking by mysql and create major issue in database. We can use it only we are sure its impact for example we want to delete some rows from master table even child table contains corresponding rows and we are fine with this etc.

Categories