I have an error saving the data in my database in two different tables. but with the same ID_USER however one is a primary key and the other unique.
I need that when creating the user it can automatically generate the ID_USER for the other table and save its password. How do I rescue the ID_USER from the previous table to insert it in another? since when I run it I get an error
"Cannot add or update a child row: a foreign key constraint fails (tests``private, CONSTRAINT private_ibfk_1 FOREIGN KEY (ID_USER) REFERENCES user (ID_USER) ON DELETE CASCADE ON UPDATE CASCADE)"
is this possible to do?
private void insertarActionPerformed(java.awt.event.ActionEvent evt) {
int val = 0;
String user, pass = "";
user = jTextField_user.getText().trim();
pass = jTextField_pass.getText().trim();
if (user.equals("")) {
val++;
}
if (pass.equals("")) {
val++;
}
if (val == 0) {
try {
Connection cn = Conexion.conectar();
PreparedStatement pst = cn.prepareStatement(
"Insert into user (ID_USER,USER) values (?,?)");
pst.setInt(1, 0);
pst.setString(2, user);
pst = cn.prepareStatement(
"Insert into private (ID_USER,PASSWORD) values(?,?)");
pst.setInt(1, 0);
pst.setString(2, pass);
pst.executeUpdate();
cn.close();
JOptionPane.showMessageDialog(null, "Successful registration");
} catch (Exception e) {
System.err.println("Error user" + e);
}
}
}
solved . create variable ID. and bring it with a ResultSet the LAST_INSERT_ID ()
private void insertarActionPerformed(java.awt.event.ActionEvent evt) {
int id = 0, val = 0;
String user, pass = "";
user = jTextField_user.getText().trim();
pass = jTextField_pass.getText().trim();
if (user.equals("")) {
val++;
}
if (pass.equals("")) {
val++;
}
if (val == 0) {
try {
Connection cn = Conexion.conectar();
PreparedStatement pst = cn.prepareStatement(
"Insert into user values (?,?)");
pst.setInt(1, 0);
pst.setString(2, user);
pst.executeUpdate();
ResultSet rs = pst.executeQuery("select ID_USER from user where ID_USER = LAST_INSERT_ID() ");
if (rs.next()) {
id = rs.getInt("ID_USER");
}
pst = cn.prepareStatement(
"Insert into private values(?,?)");
pst.setInt(1, id);
pst.setString(2, pass);
pst.executeUpdate();
cn.close();
JOptionPane.showMessageDialog(null, "Successful registration");
} catch (Exception e) {
System.err.println("Error user" + e);
}
}
}
CREATE TRIGGER user
BEFORE INSERT ON private
FOR EACH ROW
BEGIN
IF new.ID_USER IS NULL THEN
SET new.ID_USER = ID_USER();
END IF;
END
;;
Related
My program prompts the user to enter an ID and then enter a new amount for the ID they selected, when they enter a new amount it writes a new row to the database, what I want to do is when they enter that new amount I want it to delete the existing data about the user so it doesn't write the same information to the database with just a new value.
Player updatedPlayer = null;
System.out.println("Enter the player ID:");
String playerId = FileUtility.getInput().nextLine();
System.out.println("Here are the players");
//theList = loadCampersFromDatabase(theList);
for (Player camper : PlayerDAO.selectAllById(playerId)) {
System.out.println(camper);
System.out.println("Enter the new amount paid");
newAmount = FileUtility.getInput().nextInt();
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
String sql = "DELETE FROM Camper WHERE id = ?, INSERT INTO `Camper`(`id`, `firstName`, `lastName`, `parentsName`,`phoneNumber`,`email`,`amountPaid`) "
+ "VALUES (?,?,?,?,?,?,?)";
try {
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(sql);
preparedStatement.setInt(1, camper.getRegistrationId());
preparedStatement.setString(2, camper.getFirstName());
preparedStatement.setString(3, camper.getLastName());
preparedStatement.setString(4, camper.getParentsName());
preparedStatement.setInt(5, camper.getPhoneNumber());
preparedStatement.setString(6, camper.getEmail());
preparedStatement.setInt(7, MainClass.getNewAmount());
// execute update SQL stetement
preparedStatement.executeUpdate();
System.out.println("Record is updated to DBUSER table!");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
}
I am using JDBC and mySQL to do an application for a family. After logging in into the system, the user can register for a family account. By SQL statement, I want to ensure that the input they keyed in is not repeated and they can only register when the database have a NRIC of them individually. I am working with JDBC and implementing the SQL statement in Java also. For now my problem is the system does not validate the input the user keys in and let's the information to be passed to database easily. Would appreciate some help!
*NRIC = Identity Card No
Snapshots of Database:
User Database
Family Account Database
Code
public boolean regFamily(FamilyAccount myFam, Customer myCust) throws Exception {
int fid = 0;
try {
String selectStatement2 = "SELECT * from familyok.user where nric = ? and familyid is NOT NULL ";
PreparedStatement pStmt2 = con.prepareStatement(selectStatement2);
pStmt2.setString(1, myCust.getNric());
ResultSet rs2 = pStmt2.executeQuery();
if (rs2.next()) {
String insertStatement = "Insert into familyok.familyaccount (familyname, fnric1, fnric2, fnric3)";
insertStatement = insertStatement + "values (?,?,?,?)";
PreparedStatement prepStmt = con.prepareStatement(insertStatement);
prepStmt.setString(1, myFam.getFamilyname());
prepStmt.setString(2, myFam.getFnric1());
prepStmt.setString(3, myFam.getFnric2());
prepStmt.setString(4, myFam.getFnric3());
int status = prepStmt.executeUpdate();
if (status != 0) {
String selectStatement = "SELECT fid FROM familyok.familyaccount WHERE fnric1=?";
PreparedStatement pStmt = con.prepareStatement(selectStatement);
pStmt.setString(1, myFam.getFnric1());
ResultSet rs = pStmt.executeQuery();
if (rs.next()) {
System.out.println(rs.getInt("fid") + "\t");
fid = rs.getInt("fid");
String updateStatement = "update familyok.user set familyid=?, familyname1=? where nric in (?,?,?)";
PreparedStatement preparedStmt = con.prepareStatement(updateStatement);
preparedStmt.setInt(1, fid);
preparedStmt.setString(2, myFam.getFamilyname());
preparedStmt.setString(3, myFam.getFnric1());
preparedStmt.setString(4, myFam.getFnric2());
preparedStmt.setString(5, myFam.getFnric3());
int status2 = preparedStmt.executeUpdate();
System.out.println("update=" + preparedStmt.toString());
if (status2 != 0) {
System.out.println("Family Account Created");
return true;
}
}
}
}
else
{
System.out.println("Can't Register");
return false;
}
} catch (Exception ex) {
throw new Exception("Error: " + ex.getMessage());
}
return false;
}
Hi i am new to programming , i have recently stumbled across this logic error which i couldn't solve. When i click update in the UI , console display success is false.May i know how can i increment executeUpdate to 1?. Thanks in advance
public static boolean updateStaff(Staff staff) {
boolean success = false;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
//step 1 - establish connection to database
db.getConnection();
//step 2 - declare the SQL statement
dbQuery = "UPDATE staff SET staffID = ?, staffName = ?, staffPassword= ?, staffNRIC = ?, staffGender = ?, staffContactNo = ?, staffEmail = ?, dob = ?, department = ? WHERE id = ?";
pstmt = db.getPreparedStatement(dbQuery);
//step 3 - to update record using executeUpdate method
try {
pstmt.setString(1, staff.getStaffID());
pstmt.setString(2, staff.getStaffName());
pstmt.setString(3, staff.getStaffPassword());
pstmt.setString(4, staff.getStaffNRIC());
pstmt.setString(5, staff.getStaffGender());
pstmt.setInt(6, staff.getStaffContactNo());
pstmt.setString(7, staff.getStaffEmail());
pstmt.setString(8, staff.getDOB());
pstmt.setString(9, staff.getDepartment());
pstmt.setInt(10,staff.getId());
if (pstmt.executeUpdate() == 1)
success = true;
System.out.println("success" + success);
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(success);
//step 4 - close connection
db.terminate();
return success;
}
below is the UI
private void actionPerformedUpdate(){
int contact = 0;
if (validateInput()) {
contact = Integer.parseInt(txtStaffContact.getText());
// create an object of expenses based on the input values
Staff e1 = new Staff(txtStaffID.getText(), txtStaffName.getText(),txtStaffNRIC.getText(), txtStaffGender.getText(), contact , txtStaffEmail.getText() , txtStaffDOB.getText() , txtStaffDepartment.getText(),txtStaffPassword.getText());
// insert to database and check return value
if (StaffDA.updateStaff(e1) == true) {
//if(StaffController.createStaff(e1)){
JOptionPane.showMessageDialog(HMSFrame,
"Record created successfully", "Alert",
JOptionPane.INFORMATION_MESSAGE);
// reset text field for next record.
} else if(StaffDA.updateStaff(e1) == false){
JOptionPane.showMessageDialog(HMSFrame,
"Database Error. Record not created.", "Alert",
JOptionPane.ERROR_MESSAGE);
}
}
}
private boolean validateInput() {
boolean result = false;
String msg = "";
int msgType = JOptionPane.ERROR_MESSAGE;
// retrieve the user input from the text box/area provided
String staffID = txtStaffID.getText();
String staffName = txtStaffName.getText();
String staffNRIC = txtStaffNRIC.getText();
String staffGender = txtStaffGender.getText();
String StaffContactNo = txtStaffContact.getText();
String staffEmail = txtStaffEmail.getText();
String dob = txtStaffDOB.getText();
String department = txtStaffDepartment.getText();
if (staffName.length() == 0)
msg += "Please enter staff''s Full Name.\n";
try {
Integer.parseInt(StaffContactNo); // convert to Integer for time
} catch (NumberFormatException e) {
if (StaffContactNo.length() > 8)
msg += "Plese enter hours in 24 hour clock format.\n";
}
if (msg.length() == 0)
result = true;
else
JOptionPane.showMessageDialog(HMSFrame, msg, "Alert", msgType);
return result;
}
See the control after the prepared statement going to the else if(more){} block
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,passsword);
String userName = ex.getUserName();
String password = ex.getPassword();
PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
pst.setString(1, userName);
pst.setString(2, password);
int k = pst.executeUpdate();
boolean more;
if(k > 0)
{
//boolean more = rs.next();
more = true;
}
else {
more = false;
}
if(!more)
{
System.out.println("you are not a registered user!");
ex.setValid(false);
}
else if(more)
{
String firstName = rs.getString("name");
String lastName = rs.getString("rollnumber");
System.out.println("Welcome " + firstName); `control coming here`
ex.setFirstName(firstName);
ex.setLastName(lastName);
ex.setValid(true);
}
}
catch(Exception tex)
{
tex.printStackTrace();
//System.out.println("hey there is an exception " +ex);
}
The main problem is the use of int k = pst.executeUpdate();
Your query isn't an update statement, so it doesn't make sense to execute an update, it is likely that this will ALWAYS return 0, as no rows where updated.
Instead use executeQuery, which returns a ResultSet, which can use to determine if there are any rows matching your query, for example
try{
//System.out.println("iam in first line");
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection(url,user,passsword)) {
String userName = ex.getUserName();
String password = ex.getPassword();
PreparedStatement pst = con.prepareStatement("Select * from employee where username = ? and password = ? "); `after this line control is not there`
pst.setString(1, userName);
pst.setString(2, password);
try (ResultSet rs = pst.executeQuery()) {
if (rs.hasNext()) {
// Registered
} else {
// Unregistered
}
}
}
}
catch(Exception tex)
{
tex.printStackTrace();
//System.out.println("hey there is an exception " +ex);
}
You may want to take a closer look at the JDBC(TM) Database Access trail
I am trying to get this function to only insert the author if the author does not exist in the database.
If the author is already inside the 'authors' table (meaning same first name and same last name) then I want this function to not insert the author BUT I still want it to return the author's ID and I'm not sure how to do this.
Here is my insertAuthor function that inserts the author even if he already exists:
public static int insertAuthor(Connection conn, Author author) throws SQLException
{
ResultSet keys = null;
int authorId;
// Insert the new Authors into the authors table
String sqlInsertAuthor = "INSERT into authors"
+ "(author_firstname, author_lastname)"
+ " VALUES (?, ?)";
try (PreparedStatement statement = conn.prepareStatement(sqlInsertAuthor, Statement.RETURN_GENERATED_KEYS);)
{
statement.setString(1, author.getFirstName());
statement.setString(2, author.getLastName());
// Execute and return number of rows affected
int affectedRows = statement.executeUpdate();
// The number of affected rows should be equal to 1
if (affectedRows == 1)
{
keys = statement.getGeneratedKeys();
keys.next();
authorId = keys.getInt(1);
}
else
{
return 0;
}
}
catch (SQLException e)
{
System.err.println("ERROR INSERTING AUTHOR: " + e.getMessage());
return 0;
}
return authorId;
}
Well, there are several ways to do it.
You can use hibernate and it's 2nd level cache to load all authors and check the first and last name.
You can set the lastname to be unique - it would raise an error if lastname already exists.
You can do it manually - Just check if the first and last name already exists (select count where firstname and lastname). If 0 add new row.
Etc.
If you want the id the last solution would be probably the best: instead of count you could select an in - if there is none, there will be null.
Ok I managed to get what I wanted while I was attempting the select count idea by kamirru.
Here is the working code:
public static int insertAuthor(Connection conn, Author author) throws SQLException
{
ResultSet keys = null;
int authorId;
// Insert the new Authors into the authors table
String sqlInsertAuthor = "INSERT into authors"
+ "(author_firstname, author_lastname)"
+ " VALUES (?, ?)";
try (PreparedStatement statement = conn.prepareStatement(sqlInsertAuthor, Statement.RETURN_GENERATED_KEYS);)
{
// Check if author already exists, if yes return his id
authorId = authorExists(conn, author.getFirstName(), author.getLastName());
// If 0 is returned then the author does not exist so insert the author
if (authorId == 0)
{
statement.setString(1, author.getFirstName());
statement.setString(2, author.getLastName());
// Execute and return number of rows affected
int affectedRows = statement.executeUpdate();
// The number of affected rows should be equal to 1
if (affectedRows == 1)
{
keys = statement.getGeneratedKeys();
keys.next();
authorId = keys.getInt(1);
}
else
{
return 0;
}
}
}
catch (SQLException e)
{
System.err.println("ERROR INSERTING AUTHOR: " + e.getMessage());
return 0;
}
return authorId;
}
public static int authorExists(Connection conn, String firstName, String lastName) throws SQLException
{
int authorId = 0;
// Select the author to check if he exists
String sqlCountAuthor = "SELECT author_id"
+ " FROM authors"
+ " WHERE author_firstname = ? AND author_lastname = ?";
ResultSet rs = null;
try (PreparedStatement statement = conn.prepareStatement(sqlCountAuthor);)
{
statement.setString(1, firstName);
statement.setString(2, lastName);
rs = statement.executeQuery();
// If a result is returned then the author already exists so take his id
if (rs.next())
{
authorId = rs.getInt("author_id");
}
}
catch (SQLException e)
{
System.err.println("ERROR SELECTING AUTHOR: " + e.getMessage());
}
finally
{
if (rs != null)
{
rs.close();
}
}
return authorId;
}