I have a H2 DB with a table
CREATE TABLE income_expense
(
amount VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
ondate VARCHAR(255) NOT NULL
);
and some random data like INSERT INTO income_expense VALUES ('10','Something','2015-04-15');
then I connect to this DB with JDBC and try to do an UPDATE through CachedRowSet:
public void doUpdate()
{
try
{
Class.forName("org.h2.Driver");
setConnection(
DriverManager.getConnection("jdbc:h2:~/thisdb", "sa", ""));
CachedRowSet crs2 = new CachedRowSetImpl();
crs2.setType(CachedRowSet.TYPE_SCROLL_INSENSITIVE);
crs2.setConcurrency(CachedRowSet.CONCUR_UPDATABLE);
crs2.setCommand(
"SELECT amount, name, ondate FROM income_expense");
crs2.execute(getConnection());
crs2.absolute(1);
crs2.updateString("amount", "22");
crs2.updateString("name" , "33");
crs2.updateString("ondate", "44");
crs2.updateRow();
crs2.acceptChanges();
}
catch (ClassNotFoundException | SQLException e)
{
System.out.println("Error occured." + e);
}
}
this update fails with a message javax.sql.rowset.spi.SyncProviderException: 1 conflicts while synchronizing.
What am I doing wrong to update a record?
Well... CachedRowSet UPDATE worked only after I added a PRIMARY KEY to the table:
ALTER TABLE income_expenses ADD COLUMN id INT NOT NULL AUTO_INCREMENT;
ALTER TABLE income_expenses ADD CONSTRAINT PRIMARY KEY (id);
and specified numbers of columns which form a key for uniquely identifying a row and included that column in a SELECT:
//First column from a command will be the key
crs2.setKeyColumns(new int[]{1});
crs2.setCommand("SELECT id, amount, name, ondate FROM income_expense");
Related
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
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 having the table called eventUserRelationMapping in that table there is two foreign key Event_id and Ringee_User_id. this eventUserRelationMapping doesn't have a separate DO class its under the UserDO class. here I am trying to get the EventUserRelationMapping for front end use. if I get the method I got the error like this
Cannot add or update a child row: a foreign key constraint fails (`ringeeapp_dev`.`event_user_relation`, CONSTRAINT `FK_EVT_RINGEE_USER_ID` FOREIGN KEY (`RINGEE_USER_ID`) REFERENCES `ringee_user` (`RINGEE_USER_ID`))
but the data inserted in that eventUserRelationMApping table
this is my geteventUserMapping()method in DAOImpl
Override
public List<UserDO> getEventUserRelationMapping(UserDO userDO)
throws UserDataException {
JdbcTemplate jd = this.getJdbctemplate();
int isNotDeleted = IRingeeConstants.IS_NOT_DELETED;
try
{
List<UserDO> userDOs = jd.query(GET_EVENT_USER_RELATION_MAPPING, new Object[] {userDO.getRingeeUserId() , isNotDeleted }, new RowMapper<UserDO>() {
#Override
public UserDO mapRow(ResultSet rs, int rowNum) throws SQLException {
UserDO userDO = new UserDO();
userDO.setEventUserId(rs.getLong(1));
userDO.setEventId(rs.getLong(2));
userDO.setRingeeUserId(rs.getLong(3));
userDO.setAttending(rs.getInt(4));
userDO.setDeleted(rs.getInt(5));
return userDO;
}
});
return userDOs;
}catch (DataAccessException dExp) {
throw new UserDataException("Error while getting eventUserRelationMapping for user " + userDO.getRingeeUserId(), dExp);
}
}
this is query for GET_EVENT_USER_RELATION_MAPPING
private static final String GET_EVENT_USER_RELATION_MAPPING = "SELECT EVENT_USER_ID, EVENT_ID, RINGEE_USER_ID, IS_ATTENDING, IS_DELETE FROM EVENT_USER_RELATION WHERE RINGEE_USER_ID = ? AND IS_DELETE = ? ";
this is the test case of getEventUserRelationMapping
#Test
#Rollback(false)
public void testgetEventUserRelationMapping() {
ArrayList<UserDO> userDOs = new ArrayList<>();
UserDO userDO = getUserDO();
userDOs.add(userDO);
UserDO userDO1 = getUserDO1();
userDOs.add(userDO1);
EventDO eventDO = getEventDO();
eventDO.setRingeeUserId(userDO.getRingeeUserId());
try {
eventDAOImpl.addEvent(eventDO);
userDAOImpl.addEventUserRelationMapping(userDOs,
eventDO.getEventId());
List<UserDO> userDOs1 = userDAOImpl
.getEventUserRelationMapping(userDO);
Assert.assertEquals(1, userDOs1);
} catch (UserDataException uExp) {
uExp.printStackTrace();
Assert.fail();
}
}
please help me to fix this issue and why it happends
THIS IS THE MYSQL QUERY FOR EVENT TABLE
CREATE TABLE `event` (
`EVENT_ID` BIGINT(20) NOT NULL,
`RINGEE_USER_ID` BIGINT(20) NOT NULL,
`TEXT` VARCHAR(45) NOT NULL,
`PLACE` VARCHAR(45) NOT NULL,
`EVENT_DATE` DATETIME NOT NULL,
`START_TIME` VARCHAR(10) NULL DEFAULT NULL,
`END_TIME` VARCHAR(10) NULL DEFAULT NULL,
`IS_DELETE` TINYINT(1) NULL DEFAULT '0',
`CREATED_DTTM` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
`MODIFIED_DTTM` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`EVENT_ID`),
INDEX `EVENT_ID` (`EVENT_ID`),
INDEX `FK_EVENT_RINGEE_USER_ID` (`RINGEE_USER_ID`),
CONSTRAINT `FK_EVENT_RINGEE_USER_ID` FOREIGN KEY (`RINGEE_USER_ID`) REFERENCES `ringee_user` (`RINGEE_USER_ID`) ON UPDATE NO ACTION ON DELETE NO ACTION
)
THIS IS FOR EVENTUSERRELATION TABLE MYSQL QUERY
CREATE TABLE `event_user_relation` (
`EVENT_USER_ID` BIGINT(20) NOT NULL DEFAULT '0',
`EVENT_ID` BIGINT(20) NULL DEFAULT NULL,
`USER_RELATION_ID` BIGINT(20) NULL DEFAULT NULL,
`IS_ATTENDING` TINYINT(4) NULL DEFAULT NULL,
`CREATED_DTTM` TIMESTAMP NULL DEFAULT NULL,
`MODIFIED_DTTM` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`EVENT_USER_ID`),
UNIQUE INDEX `EVENIT_ID_USER_RELATION_ID` (`EVENT_ID`, `USER_RELATION_ID`),
INDEX `FK_EVT_USR_USR_REL_ID` (`USER_RELATION_ID`),
CONSTRAINT `FK_EVT_USR_USR_REL_ID` FOREIGN KEY (`USER_RELATION_ID`) REFERENCES `user_relation` (`USER_RELATION_ID`),
CONSTRAINT `FK_EVT_USR_EVT_ID` FOREIGN KEY (`EVENIT_ID`) REFERENCES `event` (`EVENT_ID`)
)
First i see an error in your #Test method
Assert.assertEquals(1, userDOs1); <==> Assert.assertEquals(1, userDOs1.size());
To avoid this SQL Error you need to insert the data in your table and the in the join table
Exemple :
(tab1, tab2, tab_12)
Insert values into tab1 (commit)
Insert values into tab2 (commit)
Insert values into tab_12 (commit)
This question already has answers here:
Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails
(21 answers)
Closed 8 years ago.
While a am trying to insert values to following table via jdbc i am getting error
Database schema
CREATE TABLE student_contact_details_t(
student_contact_details_id MEDIUMINT NOT NULL AUTO_INCREMENT,
student_id MEDIUMINT NOT NULL ,
contact_relation_type_id MEDIUMINT NOT NULL,
name varchar(255),
addresss varchar(255),
phone_no varchar(255),
created_by varchar(255),
created_date DATE,
modified_by varchar(255),
modified_date DATE,
PRIMARY KEY(student_contact_details_id),
FOREIGN KEY(student_id) REFERENCES student_details_t(student_id),
FOREIGN KEY(contact_relation_type_id) REFERENCES contact_relation_type_t(contact_relation_type_id)
);
Code
public void saveStudentContactDetails(
StudentContactDetailsTO studentContactDetails)
throws ClassNotFoundException, SQLException, IOException {
try {
int autoId = 0;
String Insertquery = "insert into student_contact_details_t(student_id,contact_relation_type_id,name,addresss,phone_no,created_by,created_date,modified_by,modified_date)values(?,?,?,?,?,?,?,?,?)";
PreparedStatement prepareStatement = JDBCConnectionUtil
.getConnection().prepareStatement(Insertquery,
Statement.RETURN_GENERATED_KEYS);
ResultSet studentId = prepareStatement.getGeneratedKeys();
prepareStatement.setInt(1, studentContactDetails.getStudentId());
// prepareStatement.setInt(2,studentId.getInt(1));
prepareStatement.setInt(2, autoId);
prepareStatement.setString(3, studentContactDetails.getName());
prepareStatement.setString(4, studentContactDetails.getAddress());
prepareStatement.setString(5, studentContactDetails.getPhoneNo());
prepareStatement.setString(6, "sysadmin");
prepareStatement.setString(7, DateUtil.getDate().format(date));
prepareStatement.setString(8, "sysadmin");
prepareStatement.setString(9, DateUtil.getDate().format(date));
prepareStatement.executeUpdate();
while (studentId.next()) {
autoId = studentId.getInt(1);
System.out.println(autoId);
}
} catch (ClassNotFoundException | SQLException | IOException e) {
throw e;
}
}
Exception
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`studentregistration`.`student_contact_details_t`, CONSTRAINT `student_contact_details_t_ibfk_1` FOREIGN KEY (`student_id`) REFERENCES `student_details_t` (`student_id`))
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.Util.getInstance(Util.java:360)
The error says that you are inserting student_id in table student_contact_details_t that does not exist in student_details_t table voilating the foreign key constraint that you set up during student_contact_details_t table creation.
So you have to first insert in table student_details_t then insert in student_contact_details_t with student_id
You have to validate that the student id exist in the student table student_details_t.
If the student doesn't exist in student_details_t then you can't insert in the related table student_contact_details_t.
In this scenario you should tell the user that "student XXX doesn't exist".
Mysql tables
mysqltables
This is my query to insert data to the database.
public void voegSpelerToe(Speler speler, String spelNaam)
{
PreparedStatement invoerSpeler;
Speler huidigeSpeler = null;
try
{
Connection connection = PersistentieController.getInstance().getConnection();
invoerSpeler = connection.prepareStatement("INSERT INTO Speler " + "(naam, kleur, sector, aantalZilverstukken, Spel_naam) " + "VALUES ( ?, ?,?, ?, ?)");
invoerSpeler.setString(1, speler.getNaam());
invoerSpeler.setString(2, speler.getKleur());
invoerSpeler.setInt(3, speler.getSector().getCode());
invoerSpeler.setInt(4,speler.getKrediet());
invoerSpeler.setString(5, spelNaam);
invoerSpeler.executeUpdate();
} catch (SQLException sqlException)
{
sqlException.printStackTrace();
} finally
{
// PersistentieController.getInstance().closeConnection();
}
}
Everything has a value so I don't have nullexeptions.
But when I want to save the data I get this error:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`projecteng62`.`speler`, CONSTRAINT `fk_Speler_Spel1` FOREIGN KEY (`Spel_naam`) REFERENCES `spel` (`naam`) ON DELETE CASCADE ON UPDATE CASCADE)
How can I insert data in the foreign key.
First It save data to the table Spel
and then i need to save data in the table speler but I get a problem wit the foreign Key.
Like table spel:
naam: Game12
aantalTeSPelenRondes: 2
table Speler:
naam : player1
kleur : green
sector : 2
aantalZilverStukken : 10
Spel_Naam: game12
Spel_naam must be the same as naam in table Spel
It is telling you that it is expecting the contents of Spel_Naam to exist in some row in spels naam attribute, but it does not exist.
To fully figure out the issue I would also need to see where you are inserting into spel.
But in the example input you provided
naam: Game12
Spel_Naam: game12
there is an issue because one is capitalized and the other is not. If this is actually how the data is set up, then that is likely your problem. But it seems you have the right idea, you need to insert into naam first, then into Spel_Naam.