unique constraint violated? - java

i'm trying to update a table:
create table Out_Patient(Patient_ID number(8) primary key ,
First_Name varchar2(20) ,
Last_Name varchar2(20) ,
Gender varchar2(10) ,
Mobile_Number number(12) ,
Address varchar2(20),
Date_Of_Birth Date ,
Date_Of_Entry Date)
with foll. code:
PreparedStatement st= con.prepareStatement("Update Out_Patient Set Patient_ID=?,First_Name=?,Last_Name=?,Gender=?,Mobile_Number=?,Address=?,Date_Of_Birth=?,Date_Of_Entry=?");
String t1=text1.getText();
int id=Integer.parseInt(t1);
String t2=text2.getText();
String t3=text3.getText();
String t4=text4.getText();
String t5=text5.getText();
String t6=text_dob.getText();
String t7=text_doe.getText();
String s1=combo_gender.getSelectedItem().toString();
st.setInt(1,Integer.parseInt(t1));
st.setString(2,t2);
st.setString(3,t3);
st.setString(4,s1);
st.setString(5,t5);
st.setString(6,t4);
st.setString(7,t6);
st.setString(8,t7);
st.executeUpdate();
But i'm getting ORA-00001: unique constraint violated.
I know Patient_ID is primary key in table,but while entering details i'm keeping it same as the one in the table.What changes should be made.
Please help!!
Thanks..

Theres no WHERE clause in your JDBC update statement, therefore you're trying to set the same ID for all records. Take a look at this example: Creating a PreparedStatement Object

Related

#0001: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0)

I want to delete a row. My TABLES are 'goal' and 'contribute'.It shows above error.
Please tell immediately what's the problem.
Table structure is ,
//goal TABLE
CREATE TABLE `goal` (`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(555) NOT NULL,
`target_value` double NOT NULL,
`target_date` date NOT NULL,
`created_date` datetime NOT NULL,
`status` int(11) NOT NULL,
PRIMARY KEY (`id`))
ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8
COLLATE=utf8mb4_0900_ai_ci
//Contribute TABLE
CREATE TABLE `contribute`
(`id` int(11) NOT NULL AUTO_INCREMENT,`goal` int(11) NOT NULL,
`amount` double NOT NULL, `date` date NOT NULL,
PRIMARY KEY (`id`),KEY `idgoal_idx` (`goal`),
CONSTRAINT `fk` FOREIGN KEY (`goal`) REFERENCES `goal` (`id`))
ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8m
COLLATE=utf8mb4_0900_ai_ci
//Code
public static boolean delete(int id) {
try {
Connection con = DB.getConnection();
String sql = "ALTER TABLE 'goal' ADD CONSTRAINT 'fk' FOREIGN
KEY('goal') REFERENCES 'goal' ('id') ON DELETE CASCADE ";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
return true;
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
In my oppinion your code is bad. You are executing this
String sql = "ALTER TABLE 'goal' ADD CONSTRAINT 'fk' FOREIGN
KEY('goal') REFERENCES 'goal' ('id') ON DELETE CASCADE ";
every time you invoke this method. You should add constraints when creating the tables.
In order to delete a row from some table i suggest you to create a database procedure or function which does it and invoke it through java.
String sql = "{? = call your_schema.your_package.delete_object(?)}";
try (CallableStatement cs = con.createCallableStatement(sql)) {
cs.setInt(1, id);
cs.executeQuery();
}
This is just an example but i think this is the correct way to do it. In this procedure you accept your ID as parameter and delete the row there.
Here's two problem:
1.your sql doesn't contain any parameter keyword : ?
You use java set parameter ps.setInt(1, id), but your sql doesn't contain keyword ?
Example for parameter using ? :
PreparedStatement p = con.prepareStatement("select * from xxxTable where xxx = ?");
p.setString(1, xxx);
More details you can learn from mysql - java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) - Stack Overflow
2.Your SQL maybe wrong
ALTER TABLE 'goal' ADD CONSTRAINT 'fk' FOREIGN
KEY('goal') REFERENCES 'goal' ('id') ON DELETE CASCADE
'goal' table doesn't contain 'goal' column.
it should be changed like:
ALTER TABLE `contribute`
ADD FOREIGN KEY (`goal`) REFERENCES `goal`(`id`) ON DELETE CASCADE ;
SQL Fiddle Demo Link

Java & SQL - Can't create duplicate values in my primary and foreign key

Go easy on me, middle school teacher taking a CS class. I've got a Java program that asks for user name, height, weight, does some calculations and gives results to the user. I now need to store this data in a database. I can get the data to store until I start using primary and foreign keys.
Here is the error I can't figure out:
Error: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL180429151131780' defined on 'USERPROFILE'.
Here is my table:
drop table stayfitapp.userdata;
drop table stayfitapp.userprofile;
drop schema stayfitapp restrict;
create schema stayfitapp;
create table stayfitapp.userprofile
(
profileName varchar(255) not null primary key,
profileGender varchar(255) not null
);
create table stayfitapp.userdata
(
profileAge double not null,
profileWeight double not null,
profileHeight double not null,
profileWaistCircumference double not null,
profileHipCircumference double not null,
profileName varchar(255),
foreign key (profileName) references stayfitapp.userprofile(profileName)
);
Here is the section of the "app" that writes to the table...
public void save(){
try {
String query = "insert into stayfitapp.userprofile" + "(profileName, profileGender)" + "values" + "(?,?)";
String query2 = "insert into stayfitapp.userdata" + "(profileAge, profileWeight, profileHeight, profileWaistCircumference, profileHipCircumference)" + "values" + "(?,?,?,?,?)";
Connection myConnection = DriverManager.getConnection("jdbc:derby://localhost:1527/stayfitDB2", "username", "password");
Statement myStatement = myConnection.createStatement();
//Statement myStatement2 = myConnection.createStatement();
PreparedStatement prepared = myConnection.prepareStatement(query);
prepared.setString(1, profileName);
prepared.setString(2, profileGender);
PreparedStatement prepared2 = myConnection.prepareStatement(query2);
prepared2.setDouble(1, profileAge);
prepared2.setDouble(2, profileWeight);
prepared2.setDouble(3, profileHeight);
prepared2.setDouble(4, profileWaistCircumference);
prepared2.setDouble(5, profileHipCircumference);
int rowsAffected = prepared.executeUpdate();
int rowsAffected2 = prepared2.executeUpdate();
if(rowsAffected==0)
{
System.out.println("Warning: User data did not save!");
}
else
{
System.out.println("User info saved!");
}
}
catch(SQLException e)
{
System.out.println("Error: "+e.toString());
}
Your save() method will attempt to add the user to the stayfitapp.userprofile table. This table has a field called profileName. profileName is the "primary key" so no duplicate values are allowed.
The error that you are getting is saying that you cannot add(insert) the record to the table because the table already has a record with the same name.
Does your program work okay if you use a different name each time?
You will need to add some logic to your program to deal with the scenario where the profileName already exists in the table. This will probably involve deleting or updating the existing record.
This is the problem.
insert into stayfitapp.userprofile"
+ "(profileName, profileGender)" + "values" , etc
You have nothing to check to see if a record already exists. Something like this would work better.
insert into stayfitapp.userprofile
profileName, profileGender
select distinct ?, ?
from someSmallTable
where not exists (
select 1
from stayfitapp.userprofile
where profileName = ?
)
The someSmallTable bit depends on your database engine, which you didn't specify.
I ended up writing a method to check if the username was already in the profile table. If the username was a duplicate I only wrote to the data table. If the username was new I wrote to both tables.
Thank you for your help! I'm sure there was a more efficient method (figuratively and literally) but I'm on to my final project and nearly surviving an actual CS class.

Cannot insert object to HSQLDB with ActiveJDBC

I'm trying to use ActiveJDBC with HSQLDB:
Users.sql
CREATE TABLE users (
"ID" INTEGER GENERATED BY DEFAULT AS SEQUENCE seq NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(100) NOT NULL,
LAST_NAME VARCHAR(100) NOT NULL
);
User.java
#IdName("ID")
public class User extends Model {....}
Main.java
User u = new User();
u.setFirstName("first_name");
u.setLastName("last_name");
u.save();
And when I try to save new row I have the following exception:
org.javalite.activejdbc.DBException: java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: id, Query: INSERT INTO users (first_name, last_name) VALUES (?, ?), params: first_name,last_name
I think that problem in lower case in insert query. How I can fix this problem?
After googling for this HSQL exception message, I threw this code together that actually works. It uses ActiveJDBC, works with plain query and also works with instrumented model:
Base.open("org.hsqldb.jdbc.JDBCDriver", "jdbc:hsqldb:file:./target/tmp/hsql-test", "sa", "");
String create = "CREATE TABLE people (\n" +
" ID INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1) NOT NULL,\n" +
" FIRST_NAME VARCHAR(100) NOT NULL,\n" +
" LAST_NAME VARCHAR(100) NOT NULL\n" +
");";
Base.exec(create);
Base.exec("INSERT INTO people (first_name, last_name) VALUES (?, ?)", "John", "Doe");
System.out.println("===>" + Base.findAll("select * from people"));
Person p = new Person();
p.set("first_name", "Jane", "last_name", "Doe").saveIt();
System.out.println(Base.findAll("select * from people"));
System.out.println(Person.findAll());
Base.close();
As you can see, the code that creates a table is a bit different, especially around the ID column.
The model looks like this:
#IdName("ID")
public class Person extends Model {}
Basically, you had the following issues with your code:
Definition of ID column with double quotes
ID column needs to be defined as IDENTITY (do not hold my feet to the fire, I'm no HSQL expert, but t works)
The model needs to overwrite the #IdName("ID"), since ActiveJDBC defaults to lower case id, unless you change that in the table (why not?)
Keep in mind, that some things may not work, since HSQL is not on a list of supported databases.
I hope this helps!
CREATE TABLE users (
ID INTEGER GENERATED BY DEFAULT AS SEQUENCE seq NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(100) NOT NULL,
LAST_NAME VARCHAR(100) NOT NULL
);

Phantom MySQLIntegrityConstraintViolationException between two CallableStatementS

We got strange non-permanent error: MySQLIntegrityConstraintViolationException inside java transaction.
Imagine next code:
sql:
CREATE TABLE test (
ruleID INT(11) NOT NULL AUTO_INCREMENT,
name varchar(250),
PRIMARY KEY (ruleID)
) engine=InnoDB;
CREATE TABLE test2 (
ruleID INT(11) NOT NULL,
name varchar(250),
PRIMARY KEY (ruleID),
CONSTRAINT _FK1 FOREIGN KEY (ruleID)
REFERENCES test (ruleID)
ON DELETE CASCADE
) engine=InnoDB;
CREATE PROCEDURE proc1(
inout p_ruleID INT (11),
p_name varchar(250)
)
proc: begin
IF (p_ruleID < 1) THEN
INSERT INTO test (ruleID, name) values (null, p_name);
SELECT LAST_INSERT_ID() INTO p_ruleID;
else
UPDATE test
SET name = p_name
WHERE ruleID = p_ruleID;
SELECT p_ruleID;
END IF;
END //
CREATE PROCEDURE proc2(
p_ruleID INT (11),
p_name varchar(250)
)
BEGIN
DELETE FROM test2
WHERE ruleID = p_ruleID;
INSERT INTO test2(ruleID, name)
VALUES (p_ruleID, p_name);
END //
java:
Connection conn;
int id;
String name;
String subName;
...
conn.setAutoCommit(false);
id=1;
CallableStatement cs1 = conn.prepareCall("{call proc1(?,?)}");
cs1.setInt(1, id);
cs1.setString(2, name);
cs1.registerOutParameter(1, java.sql.Types.INTEGER);
cs1.execute();
int parentID = cs1.getInt(1);
cs1.close();
cs1 = conn.prepareCall("{call proc2(?,?)}");
cs1.setInt(1, parentID);
cs1.setString(2, subName);
cs1.execute();
...
So once during the "cs1.execute()" for "proc2" we got exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:
Cannot add or update a child row:
a foreign key constraint fails (test2, CONSTRAINT '_FK1' FOREIGN KEY ('ruleID') REFERENCES 'test' ('ruleID') ON DELETE CASCADE)
We got it only once and can't repeat it.
One "guru" said - java transaction, performed by Connection, don't garanty the visibility of results between CallableStatementS.
Is it true? Or may be the truth is out there?

Oracle JDBC and Views

I am trying to get SELECT statement from a view with executeQuery but i cant get a resultset, the meta data is intact (names and number of columns)
i am also tried change to PreparedStatement and CallableStatement and it is the same
Here is my code
private Statement stmt=null;
private ResultSet rset=null;
........
rset = stmt.executeQuery("SELECT STUDENT_ID,FIRST_NAME,LAST_NAME FROM STUDENT_VIEW");
columnNum=rset.getMetaData().getColumnCount();
toClient.writeInt(columnNum);
for(int i=1;i<=columnNum;i++)
toClient.writeUTF(rset.getMetaData().getColumnName(i));
if (rset.last()) {
toClient.writeInt(rset.getRow());
rset.beforeFirst();
}
while (rset.next())
for(int i=1;i<=columnNum;i++){
if(rset.getString(i)!=null)
toClient.writeUTF(rset.getString(i));
else
toClient.writeUTF(" ");
}
in the debug mode java can't execute rset.last() command
but when i do
rset = stmt.executeQuery("SELECT * FROM STUDENT_VIEW")
the code run perfectly.
Can some one help?
the STUDENT_VIEW
CREATE OR REPLACE VIEW STUDENT_VIEW
AS
SELECT
s.student_id,s.first_name,s.last_name,s.phone,s.birth_date,s.street,
s.zip_code,d.name as Department,d.credits_to_degree,s.credits,s.eligible,c.name as College
FROM
STUDENT s,DEPARTMENT d,COLLEGE c
WHERE
s.department=d.department_id and d.college_id=c.college_id;
The other tables
create table Department (
Department_ID varchar(4) not null,
Name varchar(25) unique,
Department_Head_ID varchar(9),
College_ID varchar(4),
Credits_To_Degree NUMBER(3),
Students NUMBER(3),
Faculty NUMBER(3),constraint pkDepartment primary key (Department_ID));
ALTER TABLE Department ADD FOREIGN KEY (Department_Head_ID) REFERENCES Faculty(Faculty_Id) INITIALLY DEFERRED;
ALTER TABLE Department ADD FOREIGN KEY(College_ID) REFERENCES College(College_ID) INITIALLY DEFERRED;
create table Student (
Student_ID varchar(9) not null,
First_Name varchar(25),
Last_Name varchar(25),
Phone char(11),
Birth_Date date,
Street varchar(100),
Zip_Code char(5),
Department varchar(4),
Credits integer,
Eligible char(4), constraint pkStudent primary key (Student_ID),constraint fkDeptId foreign key (Department) references Department(Department_ID));
create table College(
College_ID varchar(4) not null,
Name varchar(25),
Since date,
Dean_ID varchar(9),constraint pkCollege primary key (College_ID));

Categories

Resources