first sry if i do any grammar mistakes my motherlanguage is not English.
Here im printing out all the customers from database, and for each table row i add delete link which takes customers code as a parameter. When clicking on the link it should delete one row but it deletes all the customers with the same code, any ideas how can i delete just one row even if there are customers with same code?
for(Customers customer : customers)
{
String param = customer.getCode();
request.setAttribute("value3",param);
out.println(
"<tbody><tr> "
+ "<td>"+ customer.getFirst_name()+" "+"</td>"
+ "<td>"+ customer.getSurname()+" "+"</td>"
+ "<td>"+ customer.getCode()+" " +"</td></br>"
+ " "+"<td><a href='"+request.getContextPath()+"/Search?id="+param+"'>Delete</a></td></tr>"
);
dao.deleteCustomer(request.getParameter("id"));
}
Deleteing method :
public void deleteCustomer(String code)
{
try{
pst = getConnection().prepareStatement("delete from customer where "
+" code = '"+code +"'");
pst.executeUpdate();
}catch(Exception e)
{
throw new RuntimeException(e);
} finally {
closeResources();
}
}
Schema file :
CREATE SEQUENCE seq1 AS INTEGER START WITH 1;
CREATE TABLE customer (
id BIGINT NOT NULL PRIMARY KEY,
first_name VARCHAR(255) NOT NULL,
surname VARCHAR(255) NOT NULL,
code VARCHAR(255) NOT NULL,
);
INSERT INTO customer VALUES(NEXT VALUE FOR seq1,'Jane','Doe','123');
INSERT INTO customer VALUES(NEXT VALUE FOR seq1,'John','Doe','456');
INSERT INTO customer VALUES(NEXT VALUE FOR seq1,'Jack','Smith','789');
You should delete the customer based on their ID in the database rather than their code.
A user ID should always be unique, where a code may not be.
An example of your data might help further.
Try:
pst = getConnection().prepareStatement("DELETE FROM customer WHERE code = '"+ code + "' and id IN (select * from (SELECT MAX(c.id) FROM customer c where code = '"+ code + "') as d)");
Related
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.
I am working on a option in a Menu function that posts the car for the sale in a database. The option asks for the user to enter the year, make, condition and price, which is then inserted into the table car_sale in the database. However, a unique listing_no must also be generated during this option. I cannot define my tables to uniquely generate the 10 digit number the option but I must code the program to insert uniquely generated listing_no. Below you will find the code of me trying to do this, however the code only works in Oracle but I cannot use Oracle. I can only PostGreSQL and Java. Therefore, my problem arises as the functions and relations I am using cannot be used in PostGre.
Code to Generate Listing No:
public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(sysdate,'yyyymmdd')||AUDIT_SEQ.NEXTVAL)valnext from dual");;
if(result.next())
{
listingSeq = result.getInt(1);
}
int seq = listingSeq;
return seq;
}
Code in The Option Function to insert the lisitng_no generated from generateListingNo()
public void option() throws SQLException
{
int listing_no = generateListingNo();
// insert information into books_for_sale table
sql_insert = "INSERT INTO car_sale VALUES(" + listing_no +", "
+ "'" + year + "'" + ", " +
"'" + make + "'" +", " +
"'" + condition + "'" + ", "
+ price + ")";
Erros I am Getting:
Exception in thread "main" org.postgresql.util.PSQLException: ERROR: relation "dual" does not exist
Position: 69 at
org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:217)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:421)
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:318)
at org.postgresql.jdbc.PgStatement.executeQuery(PgStatement.java:281)
Creating the car_sale table
create table car_sale(
listing_no int not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),
Change you query for generateListingNo as below:
select q from (select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ') )q )sq
or
select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval
or on your cocde:
public int generateListingNo() throws SQLException
{
int listingSeq = 0;
Statement select = connection.createStatement();
result = select.executeQuery("select (to_char(now(),'yyyymmdd') || NEXTVAL('AUDIT_SEQ')) as newseqval");;
if(result.next())
{
listingSeq = result.getInt(1);
}
int seq = listingSeq;
return seq;
}
Since you dont have sequence :
Either create sequence using below query:
CREATE SEQUENCE public."AUDIT_SEQ"
INCREMENT 1
START 1
MINVALUE 1
MAXVALUE 9223372036854775807
CACHE 1;
or use UUID:
public String generateListingNo() throws SQLException
{
return UUID.randomUUID().toString();
}
your table structure will need to change :
create table car_sale(
listing_no varchar not null,
year varchar not null,
make varchar not null,
condition varchar not null,
price decimal(12,2) not null,
primary key (listing_no),
For PostgreSQL, you have to call query this way from java :
SELECT nextval('ACCOUNT_TRANSACTION_NO')
I'm trying to update a table with prepared statement, but I get the error:
ERROR fremad.dao.JdbcUserDao - com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '21' for key 'PRIMARY'
I really don't get it because I'm not trying to add more rows.
This is the table:
CREATE TABLE `user_meta` (
`user_id` INT(16) NOT NULL ,
`first_name` VARCHAR(32) NOT NULL ,
`last_name` VARCHAR(32) NOT NULL ,
`phone_number` VARCHAR(16) ,
`birthday` DATE ,
`home_town` VARCHAR(32) ,
`profession` VARCHAR(32) ,
CONSTRAINT `fk_user_meta_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
PRIMARY KEY ( `user_id` )
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This is the function:
#Override
public UserMetaObject updateUserMeta(UserMetaObject userMetaObject) {
String sql = "UPDATE " + SqlTablesConstants.SQL_TABLE_NAME_USER_META + " SET "
+ "first_name = ?, "
+ "last_name = ?, "
+ "phone_number = ?, "
+ "birthday = ?, "
+ "home_town = ?, "
+ "profession = ? "
+ "WHERE user_id = ?";
connect();
try {
prpstm = conn.prepareStatement(sql);
prpstm.setString(1, userMetaObject.getFirstName());
prpstm.setString(2, userMetaObject.getLastName());
prpstm.setString(3, userMetaObject.getPhoneNumber());
prpstm.setDate(4,userMetaObject.getBirthday());
prpstm.setString(5, userMetaObject.getHomeTown());
prpstm.setString(6, userMetaObject.getProfession());
prpstm.setInt(7, userMetaObject.getUserId());
prpstm.executeUpdate();
} catch (SQLException e) {
LOG.error(e.toString());
return null;
} finally {
close();
}
return userMetaObject;
}
And when I tried to paste this directly in to the terminal and it succeeded:
UPDATE user_meta SET first_name = "John", last_name = "Doe", phone_number = "81549300", birthday = "1988-05-24 00:00:00", homeTown = "Lillehammer", profession="Student" WHERE user_id = 21;
What am I doing wrong? Please tell me if you need any more info..
When you tried your query in console there was user_id=5, but you get exception with user_id=21. It seems that you already has row with user_id=21!
When I have strange behaviors like this, it is common that the problem might be related to some trigger that you might not be aware of, if not, I would suspect from the fact that your primary key is also a foreign key, some databases have problems with that.
I have column family that have two primary keys
"CREATE TABLE compositkeys(user_name varchar," +
"user_id int,"+
"name varchar," +
"gender varchar," +
"PRIMARY KEY (user_name,user_id)" +
")";
I have created this in Java now i inserted 6 rows with on one user_name(sunil) primarykey with different id now when I try to retrieve all the value in sunil primary key it gives me only one detail
String qry = "select * from compositkeys where user_name = 'sunil' order by user_id";
Statement smt = con.createStatement();
//smt.executeUpdate(qry);
ResultSet rs = smt.executeQuery(qry);
//rs.get
int r = rs.getRow();
System.out.println(r);
ResultSetMetaData rm = rs.getMetaData();
int columnCount = rm.getColumnCount();
System.out.println(columnCount);
for(int i=1;i<=columnCount;i++)
{
String name = rm.getColumnName(i);
System.out.print(rm.getColumnName(i));
System.out.println(" = "+rs.getString(name));
System.out.println("--------------------------------------------------");
}
It gives me only one output. Is there any thing wrong in query? I want all the data under the key sunil.
You have a single loop that loops over the columns in a returned row, but you only ask for one row (that's the rs.getRow() method). You should put the rs.getRow() call and the following logic to write the results into an outer loop that iterates as long as getRow() doesn't return null. This out loop is what will retrieve all of a user's ids.
I have an application that I am working on that will query a database and display the results. The program also makes changes to the database (update, delete, insert). I had most of these features working correctly until recently when I made some changes. Now I am getting an SQLException that tells me I am violating a foreign key constraint. I have looked it up and found out that the violation is a result of more than one table sharing data. Is there a way to overcome this? How would I make the update without violating the constraint? here is my update method:
InstructorEditorPanel updateEditorPanel = new InstructorEditorPanel();
updateEditorPanel.setFieldText(InstructorEditorPanel.FieldTitle.B_NUMBER, updBNumber);
updateEditorPanel.setFieldText(InstructorEditorPanel.FieldTitle.FIRST_NAME, updFName);
updateEditorPanel.setFieldText(InstructorEditorPanel.FieldTitle.LAST_NAME, updLName);
int result = JOptionPane.showConfirmDialog(null, updateEditorPanel,
"Update Instructor", JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE);
if(result == JOptionPane.OK_OPTION)
{
for (InstructorEditorPanel.FieldTitle fieldTitle : InstructorEditorPanel.FieldTitle
.values()) {
bNum = getBNumber(updateEditorPanel.getFieldText(fieldTitle.values()[0]));
fName = getFirstName(updateEditorPanel.getFieldText(fieldTitle.values()[1]));
lName = getLastName(updateEditorPanel.getFieldText(fieldTitle.values()[2]));
}
try
{
connection = DriverManager.getConnection(URL);
updateInstructor = connection.prepareStatement(
"UPDATE Instructor SET BNUMBER = ?, FIRSTNAME = ?, LASTNAME = ? WHERE BNUMBER = ?");
}catch(SQLException sqlException){
sqlException.printStackTrace();
System.exit(1);
}//end catch
try
{
updateInstructor.setString(1, bNum);
updateInstructor.setString(2, fName);
updateInstructor.setString(3, lName);
updateInstructor.setString(4,mNumber);
updateInstructor.executeUpdate();
}catch(SQLException sqlException){
sqlException.printStackTrace();
}//end of catch
finally
{
close();
}//end
}
Display(panel); }
I had the method working without any problems until recently when I made some changes. I don't know what I did, but now I am getting the foreign key constraint violated exception
here is the exception:java.sql.SQLIntegrityConstraintViolationException: UPDATE on table 'INSTRUCTOR' caused a violation of foreign key constraint 'SQL120408141918440' for key (1234500000). The statement has been rolled back.
database info
CREATE TABLE Instructor (
BNumber varchar(10) NOT NULL,
FirstName varchar(20),
LastName varchar(30),
PRIMARY KEY (BNumber)
);
CREATE TABLE Section (
CRN int NOT NULL,
Term varchar(6) NOT NULL,
SectionNumber varchar(3),
CourseID varchar(9),
Enrollment smallint,
BNumber varchar(10),
PercentResp numeric(5,2),
CONSTRAINT CRN_Term PRIMARY KEY (CRN,Term),
FOREIGN KEY (CourseID) REFERENCES Course (CourseID),
FOREIGN KEY (BNumber) REFERENCES Instructor (BNumber)
);
INSERT INTO Instructor (BNumber, FirstName, LastName)
VALUES
('0000012345','Bill','Smith'),
('0000023456','Sue','Taylor'),
('0000034567','Skilar','Ramsey'),
('1234500000','Sam','Jones'),
('2345600000','Tyson','Quilez');
INSERT INTO Section (CRN, Term, SectionNumber, CourseID, Enrollment,
BNumber, PercentResp)
VALUES
(40035,'201040','02B','CHM2210', 31,'0000034567',100),
(40001,'201040','02B','CGS1000', 27,'0000012345',100),
(40002,'201040','70B','CGS2100', 25,'0000012345',100),
(40003,'201040','71B','CGS2100', 19,'0000012345',100),
(40004,'201040','01B','COP1000', 15,'0000012345',100),
(40030,'201040','01B','BSCC1005',30,'0000023456',100),
(40031,'201040','02B','BSCC1005',25,'0000023456',100),
(40032,'201040','70B','BSCC1005',24,'0000023456',100),
(40000,'201040','01B','CGS1000', 15,'0000012345',100),
(40034,'201040','01B','CHM2210', 27,'0000034567',100);
Replace
"UPDATE Instructor SET BNUMBER = ?, FIRSTNAME = ?, LASTNAME = ? WHERE BNUMBER = ?"
With
"UPDATE Instructor SET FIRSTNAME = ?, LASTNAME = ? WHERE BNUMBER = ?"
You should not update the primary key if it's the matching condition in your update query.
You should put ON UPDATE CASCADE after the references