Java + MySQL - Overwriting rows when updating - java

I'm starting to create a database program for managing engineers, assigning calls to them and such and having this all linked together. However, I have ran into a problem where when I try to update/change a bit of information in the database through the use of my program it instead changed all the other items in the table to what it has just been changed to. For example, if I changed engineer 1's name to 'a', it would overwrite the other entities in the table so engineer 2 would have its name as 'a' now along with the properties of engineer 1.
I have attached the code I have written to update the table along with the SQL code for my database.
I'd appreaciate if someone could help me understand what is wrong here and I can provide other information when requested.
Thanks
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try{
con = Connect.ConnectDB();
String sql = "update engineers set first_name ='" + textFirstName.getText()+ "',last_name='"+ textLastName.getText()+ "',middle_name='" + textMiddleName.getText()+ "',postcode='" + textPostcode.getText() + "',engineer_address='" + textAddress.getText() + "',engineer_dob='" + textDOB.getText() + "',comments='" + textComments.getText()+ "'";
pst = con.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(this, "Updated","Engineer",JOptionPane.INFORMATION_MESSAGE);
btnUpdate.setEnabled(false);
}catch(HeadlessException | SQLException ex){
JOptionPane.showMessageDialog(this,ex);
}
-- MySQL Script generated by MySQL Workbench
-- Fri Sep 22 12:56:05 2017
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 ;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`customers`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`customers` (
`customer_id` INT NOT NULL AUTO_INCREMENT,
`customer_name` VARCHAR(45) NOT NULL,
`telephone` VARCHAR(45) NOT NULL,
`postcode` VARCHAR(45) NOT NULL,
`address` VARCHAR(45) NOT NULL,
`city` VARCHAR(45) NOT NULL,
PRIMARY KEY (`customer_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`engineers`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`engineers` (
`engineer_id` INT NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`postcode` VARCHAR(45) NOT NULL,
`active_job` VARCHAR(45) NOT NULL,
`on_holiday` VARCHAR(45) NOT NULL,
`engineer_address` VARCHAR(45) NOT NULL,
`engineer_postcode` VARCHAR(45) NOT NULL,
`comments` VARCHAR(45) NOT NULL,
`middle_name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`engineer_id`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`machines`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`machines` (
`serial_number` VARCHAR(45) NOT NULL,
`customer_id` INT NOT NULL,
`meter_reading` VARCHAR(45) NOT NULL,
`install_date` VARCHAR(45) NOT NULL,
PRIMARY KEY (`serial_number`),
INDEX `fk_customer_id_idx` (`customer_id` ASC),
CONSTRAINT `fk_customer_id`
FOREIGN KEY (`customer_id`)
REFERENCES `mydb`.`customers` (`customer_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`new_call`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`new_call` (
`call_id` INT NOT NULL AUTO_INCREMENT,
`serial_number` VARCHAR(45) NOT NULL,
`customer_id` INT NOT NULL,
`engineer_id` INT NOT NULL,
`call_fault` VARCHAR(45) NOT NULL,
`call_type` VARCHAR(45) NOT NULL,
`date_recieved` VARCHAR(45) NOT NULL,
`start_date` VARCHAR(45) NOT NULL,
`engineer_dob` VARCHAR(45) NOT NULL,
PRIMARY KEY (`call_id`),
INDEX `fk_serial_number_idx` (`serial_number` ASC),
INDEX `fk_engineer_id_idx` (`engineer_id` ASC),
INDEX `fk1_customer_id_idx` (`customer_id` ASC),
CONSTRAINT `fk_serial_number`
FOREIGN KEY (`serial_number`)
REFERENCES `mydb`.`machines` (`serial_number`)
ON DELETE RESTRICT
ON UPDATE CASCADE,
CONSTRAINT `fk_engineer_id`
FOREIGN KEY (`engineer_id`)
REFERENCES `mydb`.`engineers` (`engineer_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE,
CONSTRAINT `fk1_customer_id`
FOREIGN KEY (`customer_id`)
REFERENCES `mydb`.`customers` (`customer_id`)
ON DELETE RESTRICT
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`users` (
`username` VARCHAR(45) NOT NULL,
`password` VARCHAR(45) NOT NULL)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;

first of all use PreparedStatement.
if you want to update a specific engineer you should identify the data with the sql where section.
in your case that could be:
PreparedStatement statement = con.prepareStatement("update engineers set first_name =? " +
",last_name=?, middle_name=?" +
",postcode=?,engineer_address=?" +
",engineer_dob=?" +
",comments=? " +
"where engineer_id=?"); // <--- WHERE SECTION
statement.setString(1, "Chuck");
statement.setString(2, "Norris");
// and so on and so on...
statement.setInteger(8, idOfEngineer);
statement.executeUpdate();

Related

Java Springboot JPA joining multiple tables

I'm new to Java Springboot and I want to join multiple tables.
I have this MySQL schema :
CREATE TABLE `users`
(
`id` int NOT NULL AUTO_INCREMENT,
`email` varchar(128) NOT NULL,
`nickname` varchar(128) NOT NULL,
`password` varchar(256) NOT NULL,CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `nickname` (`nickname`)
);
CREATE TABLE `organizations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `org_abilities`
(
`id` int NOT NULL AUTO_INCREMENT,
`key` varchar(128) NOT NULL,
`description` varchar(128) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `idx_key` (`key`) USING BTREE
);
CREATE TABLE `org_permissions`
(
`id` int NOT NULL AUTO_INCREMENT,
`id_user` int NOT NULL,
`id_organization` int NOT NULL,
`id_ability` int NOT NULL,
PRIMARY KEY (`id`),
KEY `id_organization` (`id_organization`),
KEY `id_user` (`id_user`),
KEY `users_permissions_ibfk_2` (`id_ability`),
CONSTRAINT `org_permissions_ibfk_0` FOREIGN KEY (`id_organization`) REFERENCES `organizations` (`id`),
CONSTRAINT `org_permissions_ibfk_1` FOREIGN KEY (`id_user`) REFERENCES `users` (`id`),
CONSTRAINT `org_permissions_ibfk_2` FOREIGN KEY (`id_ability`) REFERENCES `org_abilities` (`id`)
);
Where my table org_permissions represent all abilities that a user has within an organization.
I have created the corresponding Java classes. I have a JPA to fetch the datas from the DB to the classes.
I want in my Organization class to have a field Map<long, List<Pair<long, String>>> managers which map an id_user to a list of tuple of abilities where the tuple is (id_ability, org_ability.key).
Finally I use DTO to send my response, and I want my response to look like that :
{
id : _id_organization,
name : "organisation name",
managers : {
id_user: [(id_ability, key), (id_ability, key)],
id_user:[(id_ability, key), (id_ability, key)]
}
}
For example:
SELECT op.*, oa.* FROM org_permissions as op
JOIN org_abilities oa on oa.id = op.id_ability
JOIN organizations o on o.id = op.id_organization
JOIN users u on u.id = op.id_user;
Here, user with id 1 is member of organization 1 and 2. for organization 1 user 1 has the CREATE_EVENTS and DELETE_EVENTS abilities and for organization 2 he only have the DELETE_EVENTS ability.
When getting all the organization I want this result :
[{
id : 1,
name : "Org1",
managers : {
1: [(1, "CREATE_EVENT"), (2,"CREATE_EVENT")]
}
},
{
id : 2,
name : "Org2",
managers : {
1: [(2,"CREATE_EVENT")]
}
}]
Thanks for your help, I'm a bit lost with the High level of springboot and JPA
P.S.: I tried to ask to chat GPT but nothing was concluent

How to understand the "type" field in the result of using "explain" on Mysql?

When I used "explain" on Mysql to view some information about the execution of the statement, the value of the field type made me very confused!
Table creation statement
DROP TABLE IF EXISTS `actor`;
CREATE TABLE `actor` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `actor` (`id`, `name`, `update_time`) VALUES (1,'a','2017-12-2 15:27:18'), (2,'b','2017-12-22 15:27:18'), (3,'c','2017-12-22 15:27:18');
DROP TABLE IF EXISTS `film`;
CREATE TABLE `film` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `film` (`id`, `name`) VALUES (3,'film0'),(1,'film1'),(2,'film2');
DROP TABLE IF EXISTS `film_actor`;
CREATE TABLE `film_actor` (
`id` int(11) NOT NULL,
`film_id` int(11) NOT NULL,
`actor_id` int(11) NOT NULL,
`remark` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_film_actor_id` (`film_id`,`actor_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `film_actor` (`id`, `film_id`, `actor_id`) VALUES (1,1,1),(2,1,2),(3,2,1);
When I execute
explain select * from film
left join film_actor on film.id = film_actor.film_id
left join actor on actor.id = film_actor.actor_id
where film.id = 1;
The type of each table is as follows
| table | type |
| ---------- | ----- |
| film | const |
| film_actor | ref |
| actor | ALL |
When I execute
explain select * from film
left join film_actor on film.id = film_actor.film_id
left join actor on actor.id = film_actor.actor_id
The type of each table is as follows
eq_ref is interpreted as One row is read from this table for each combination of rows from the previous tables.
ref is interpreted as All rows with matching index values are read from this table for each combination of rows from the previous tables.
But the difference between these two queries is only a where condition, and no related fields are modified. Why are the types of film_actor and actor tables completely different in the two queries? How to understand this phenomenon?
Thanks in advance.

How to convert line with UNIQUE INDEX key words from mySql to H2

CREATE TABLE IF NOT EXISTS Account (
`userId` INT NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(45) NOT NULL,
`last_name` VARCHAR(45) NOT NULL,
`email` VARCHAR(45) NULL,
`ICQ` INT NULL,
`home_address` VARCHAR(45) NULL,
`work_address` VARCHAR(45) NULL,
`skype` VARCHAR(45) NULL,
`additional_info` VARCHAR(450) NULL,
PRIMARY KEY (`userId`))
UNIQUE INDEX `userID_UNIQUE` (`userId` ASC)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Account';
how to convert this line: UNIQUE INDEXuserID_UNIQUE(userIdASC) from mySQL syntax to H2 syntax ?
From the site h2database.com :
ALTER TABLE Account ADD CONSTRAINT userID_UNIQUE UNIQUE(userId);

How to insert data in Apache calcite

I'm inserting data form SQL to File through Apache calcite
Class.forName("org.apache.calcite.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:calcite:");
CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
SchemaPlus rootSchema = calciteConnection.getRootSchema();
JdbcSchema jdbcSchema = JdbcSchema.create(rootSchema, "TRUNKDB", dataSource, null, "dbo");
rootSchema.add("XXXX", jdbcSchema);
/*CSV Schema*/
File csvDir = new File("/home/nanobi/Drill/CSV/");
// SchemaPlus schema = rootSchema.add("s", new CsvSchema(csvDir,null));
rootSchema.add("CSV", new CsvSchema(csvDir, Flavor.SCANNABLE));
Statement statement = connection.createStatement();
int resultSet = statement.executeUpdate("INSERT into \"CSV\".\"p\"(\"Name\") select \"name\" from \"TRUNKDB\".\"nbmdc_nanomarts\"");
i'm getting bellow error
Exception in thread "main" java.sql.SQLException: Error while executing SQL "INSERT into "CSV"."p"("Name") select 'p' from "TRUNKDB"."nbmdc_nanomarts"": Node [rel#29:Subset#3.ENUMERABLE.[]] could not be implemented; planner state:
Root: rel#29:Subset#3.ENUMERABLE.[]
Original rel:
Sets:
Set#0, type: RecordType(VARCHAR(45) row_id, VARCHAR(45) si_id, VARCHAR(500) name, VARCHAR(500) description, VARCHAR(255) icon_path,
VARCHAR(255) icon_content, VARCHAR(255) active_flag, TIMESTAMP(3)
created_datetime, VARCHAR(45) created_by_user_id, TIMESTAMP(3)
updated_datetime, VARCHAR(45) updated_by_user_id, VARCHAR(500)
nanomart_xml_filepath, VARCHAR(255) db_username, VARCHAR(255)
db_user_password, VARCHAR(255) dbase_name, VARCHAR(255) db_url,
VARCHAR(255) db_schema_name, CHAR(1) is_mandatory, CHAR(1)
is_load_lock, VARCHAR(45) mart_type, VARCHAR(255) db_driver,
VARCHAR(255) load_frequency, CHAR(1) is_date_table, CHAR(1) is_alias,
VARCHAR(500) nbmdc_n, VARCHAR(45) master_flag, VARCHAR(50)
nbmdm_repository_row_id, CHAR(1) is_hierarchical, VARCHAR(4000)
inplacedetail)
rel#8:Subset#0.JDBC.TRUNKDB.[], best=rel#0, importance=0.6561
rel#0:JdbcTableScan.JDBC.TRUNKDB.[](table=[TRUNKDB, nbmdc_nanomarts]), rowcount=100.0, cumulative cost={100.0 rows, 101.0
cpu, 0.0 io}
Unfortunately Calcite doesn't currently support modification of CSV files. Modification has only been worked on for JDBC tables.

How to insert a foreign key in a row?

I have two tables, A and B. When inserting a new row into table B, how do I insert a FK as a reference to a record in table A?
I've got the two below tables:
--
-- Table structure for table `sector`
--
CREATE TABLE IF NOT EXISTS `sector` (
`sector_id` int(11) NOT NULL AUTO_INCREMENT,
`sector_name` varchar(100) NOT NULL,
`sector_url` varchar(500) NOT NULL,
PRIMARY KEY (`sector_id`),
UNIQUE KEY `sector_id` (`sector_id`,`sector_name`,`sector_url`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `constituent` (
`constituent_id` int(11) NOT NULL AUTO_INCREMENT,
`constituent_name` varchar(100) DEFAULT '',
`constituent_ticker` varchar(10) NOT NULL,
`constituent_isin_number` varchar(50) DEFAULT '',
`constituent_currency` varchar(10) DEFAULT '',
`sector_id` int(11) NOT NULL,
PRIMARY KEY (`constituent_id`),
KEY `sector_id` (`sector_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Constraints for table `constituent`
--
ALTER TABLE `constituent`
ADD CONSTRAINT `constituent_ibfk_1` FOREIGN KEY (`sector_id`) REFERENCES `sector` (`sector_id`);
When I do an insert, how can I structure the query such that when I insert into the table 'constituent', I'm using the primary key of 'sector'?
INSERT into constituent (constituent_name, constituent_ticker, constituent_isin_number, constituent_currency, sectorFK)
values ("the name", "the ticker", "the number", "the currency", "the foreign key???")
To be able to get a primary key value after inserting into table B, in order to insert it into the table A, you could use last_insert_id() function, which when used without a parameter returns a last automatically generated value that was set for an AUTO_INCREMENT column:
For example:
insert into B(col)
values(1);
insert into A(t1_id, col)
values(last_insert_id(), 2);
insert into A(t1_id, col)
values(last_insert_id(), 3);
SQLFIddle Demo
Assuming there is a sector with sector_name 'sector 1' you could do something like this.
INSERT into constituent (constituent_name, constituent_ticker, constituent_isin_number, constituent_currency, sector_id) (select 'the name', 'the ticker', 'the number', 'the currency', sector_id from sector where sector_name = "sector 1");

Categories

Resources