In my DB every question has a valid questionID (primary Key) and categoryID (foreign Key to category table).
The problem is: in the Result Set for every question both IDs are 0 instead of what's written in the DB. All other arguments are filled out correctly.
private ArrayList<Question> questions = new ArrayList<Question>();
private Connection connie;
private PreparedStatement psShowQuestions;
psShowQuestions= connie.prepareStatement("SELECT * FROM question");
ResultSet rs = psShowQuestions.executeQuery();
while (rs.next()) {
questions.add(new Question(rs.getInt("questionID"), rs.getInt("categoryID"), rs.getString("question"), rs.getString("rightAns"), rs.getString("wrong1"), rs.getString("wrong2"), rs.getString("wrong3"), rs.getString("hint")));
}
Collections.shuffle(questions);
Edit 1
Here is the original code (in the post I changed the variables from German to English):
The creation of my SQL table:
CREATE TABLE `frage` (
`frageID` int(11) NOT NULL,
`kategorieID` int(11) DEFAULT NULL,
`frage` varchar(200) NOT NULL,
`richtig` varchar(200) NOT NULL,
`falsch1` varchar(200) NOT NULL,
`falsch2` varchar(200) NOT NULL,
`falsch3` varchar(200) NOT NULL,
`hinweis` varchar(200) NOT NULL,
`anzFalsch` int(11) DEFAULT NULL,
`anzRichtig` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
private ArrayList<Frage> fragen = new ArrayList<Frage>();
private Connection connie;
private PreparedStatement psGetFragen;
ResultSet rs = psGetFragen.executeQuery();
while (rs.next()) {
fragen.add(new Frage(rs.getInt("frageID"), rs.getInt("kategorieID"), rs.getString("frage"), rs.getString("richtig"), rs.getString("falsch1"), rs.getString("falsch2"), rs.getString("falsch3"), rs.getString("hinweis")));
}
Collections.shuffle(fragen);
Most likely, there is a problem with the constructor. You might have not set questionID and categoryID in the constructor and therefore you are getting the default value of int as 0.
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
We are five students in a team working on a project using SCRUM methode.
Our first sprint was WEB application...
Now, we are working at the second sprint which is Desktop application with JAVA.
In the first sprint(Sprint Web),we have created our database using FOS_USER Bundle, this database contains 'User' table, his sql script is(some columns):
DROP TABLE IF EXISTS `User`;
CREATE TABLE IF NOT EXISTS `User` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(180) COLLATE utf8_unicode_ci NOT NULL,
`username_canonical` varchar(180) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(180) COLLATE utf8_unicode_ci NOT NULL,
`email_canonical` varchar(180) COLLATE utf8_unicode_ci NOT NULL,
`enabled` tinyint(1) NOT NULL,
`salt` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`last_login` datetime DEFAULT NULL,
`confirmation_token` varchar(180) COLLATE utf8_unicode_ci DEFAULT NULL,
`password_requested_at` datetime DEFAULT NULL,
`roles` longtext COLLATE utf8_unicode_ci NOT NULL COMMENT '(DC2Type:array)',
PRIMARY KEY (`id`),
UNIQUE KEY `UNIQ_1D1C63B392FC23A8` (`username_canonical`),
UNIQUE KEY `UNIQ_1D1C63B3A0D96FBF` (`email_canonical`),
UNIQUE KEY `UNIQ_1D1C63B3FF631228` (`etablissement_id`),
UNIQUE KEY `UNIQ_1D1C63B3C05FB297` (`confirmation_token`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Now, in the sprint java, we have generated the entities from database using Netbeans tool, and we get this class(some attributs):
public class User{
private Integer id;
private String username;
private String usernameCanonical;
private String email;
private String emailCanonical;
private short enabled;
private String salt;
private String password;
private Date lastLogin;
private String confirmationToken;
private Date passwordRequestedAt;
private String roles;
}
Now, we need to persist(/get to authentificate) an User object into(/from) this database, but the problem is, the password was crypted with FOS_USER Bundle.So what is the way to decrepte/encrypte this password.
Our DAOUser is like this!?
public void ajouter(User user) {
String req = "INSERT INTO User (nom,username,email,enabled,salt,password,roles) VALUES (?,?,?,?,?,?)" ;
PreparedStatement pre;
try {
pre = connection.prepareStatement(req);
pre.setString(1, user.getUsername());
pre.setString(2, user.getEmail());
pre.setShort(3, user.getEnabled());
//Some thing wrong : exp in database {username:Zain,salt:'0Yi3LZANkpfMsnhbn2XHA00cASLCGVfWc7TJWNOjXsk')
pre.setString(4, user.getSalt());
//Some thing wrong : exp in database {username:Zain,passowrd:'qXSSYBDXWQA/ZcbPVOoBKzd5oshTkQP0Q3AeEilnh47Mcrc9uUZYDYwmRJiMKc7nRPvRx6k0eEJrc6HrrDvZtQ==')
pre.setString(5, user.getPassword());
//This Role must be unserialised(the equivalent unserialize method in php)
pre.setString(6,user.getRoles());
pre.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(EtablissementService.class.getName()).log(Level.SEVERE, null, ex);
}
}
You don't wan to decrypt password. It should be one way hash. To check validity of password, encrypt user input in the same way and check calculated hash to match the hash in the database
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();
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.
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)