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;
}
Related
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
;;
so I want to Delete a record using ID but my code does not check if the ID Exists or not and I tried several method I just do not know what is the problem.
That is my code
int ID;
String DatabaseName = "jdbc:derby://localhost:1527/JobPortalDB";
String username = "DB";
String password = "1234";
String sql = " DELETE FROM Job WHERE JobID=?";
try (Connection connection = DriverManager.getConnection(DatabaseName, username, password); PreparedStatement prepstatement = connection.prepareStatement(sql)) {
ID = Integer.parseInt(jTextField1.getText());
int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete This permenantly? ", "Delete Job", JOptionPane.YES_NO_OPTION);
if (option == JOptionPane.YES_OPTION) {
prepstatement.setInt(1, ID);
prepstatement.executeUpdate();
JOptionPane.showMessageDialog(this.jTextField1, "your Operation was successfuly Done", "info", JOptionPane.PLAIN_MESSAGE);
}
if (option == JOptionPane.NO_OPTION) {
return;
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,
ex.getMessage(), "Database error",
JOptionPane.ERROR_MESSAGE);
}
You can check the existence of the ID before deleting by using the select statement and count the result.
String sql = "select * from job where job = "+JobId ;
try{
PreparedStatement ps =cnn.prepareStatement(sql) ;
ResultSet rs = ps.executeQuery(sql);
int c=0 ;
while(rs.next()){
c++ ;
}
if(c>0){
//delete
}else{JOptionPane.showMessageDialog(this.jTextField1,"user does not exist","info",JOptionPane.PLAIN_MESSAGE); }
I have it set up where I can save my object information to a SQL database using this block of code:
public boolean add(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if (aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
sqlStr.append("INSERT INTO ");
sqlStr.append(ORDER_TABLE);
sqlStr.append(" (firstName, lastName, size, cheese, sausage, ham, total)");
sqlStr.append(" VALUES (?,?,?,?,?,?,?)");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString(), Statement.RETURN_GENERATED_KEYS);
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
if (rowCount == 1) {
ResultSet rs = statement.getGeneratedKeys();
if(rs.next()) {
aOrder.setId(rs.getInt(1));
}
success = true;
}
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot save pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Insert", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
What I am trying to do is change the total variable with an update to the object on the server. I dont have an error right now popping up but nothing is changing in my objects information. Here is my code with the update block:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
//TODO create the SQL and prepared statements to update an order in the database
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET firstName = ?, lastName = ?, size = ?, cheese = ?, sausage = ?, ham = ?, total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I have it set up that just the total variable will be changed by the time the update block of code will be ran. So I was trying to just call all the variables again in the hopes that it would change the total.
I get the same results with this update block of code:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I figured out my problem I had something elsewhere in my code blocking the update. This is the code that is working to update the mySQL database in this case:
try {
//TODO create the SQL and prepared statements to update an order in the database
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ?");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
statement.setInt(2, aOrder.getId());
rowCount = statement.executeUpdate();
}
Note:
I have two columns (Name(primary key), Email(primary key))
I have inserted two rows.
The 1st row, where name=ema email=ema#gmail.com, and my 2nd row where name=ena email=fe.
Now, when I want to insert a new record it only checks with the 1st row and the checking works, but if I want to insert name=ena and email=something it does not check for the second row. Can someone please suggest to me how do I overcome this?
try
{
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/testing","root","");
//block of code to check user exists or not.
//Statement statement = connection.createStatement();
PreparedStatement Pstatement;
String query = "select Name,Email from detail";
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery() ;
if(rs.next())
{
//from database
String name_db1 = rs.getString("Name").trim(); //using trim removes all white spaces
String email_db2 = rs.getString("Email").trim();
//from user GUI
String entered_name = name.getText().trim(); //using trim removes all white spaces
String entered_email = email.getText().trim();
boolean valid = true;
if(entered_name.equals(""))
{
JOptionPane.showMessageDialog(null,"Enter name");
valid = false;
}
else if(name_db1.equals(entered_name))
{
JOptionPane.showMessageDialog(null,"Enter name taken");
name.setText(null);
valid = false;
}
else if(entered_email.equals(""))
{
JOptionPane.showMessageDialog(null,"Enter email");
valid = false;
}
else if(email_db2.equals(entered_email))
{
JOptionPane.showMessageDialog(null,"email taken");
email.setText(null);
valid = false;
}
else if(valid == true)
{
Pstatement=connection.prepareStatement("insert into detail values(?,?)");
//Specifying the values of preparestatement parameter
Pstatement.setString(1,name.getText());
Pstatement.setString(2,email.getText());
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null,"registration successful");
//x++;
}
}
else
{
//incase if the user click without filling up the fields
JOptionPane.showMessageDialog(null,"not yet registered");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
Finally, I have figured out the logic, I just need to create a separate query for both Name and Email. This way I can search more than two values :D. If there is any mistake please let me know.
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testing","root","");
//creating a query for Name
String query1 = "select Name, Email from detail where Name like '"+name.getText()+"'";
PreparedStatement statement1 = con.prepareStatement(query1);
//creating a query for Email
String query2 = "select Name, Email from detail where Email like '"+email.getText()+"'";
PreparedStatement statement2 = con.prepareStatement(query2);
ResultSet result1 = statement1.executeQuery(); //resultset for name
ResultSet result2 = statement2.executeQuery(); //resultset for email
//checking name exception
if (result1.next())
{
String dbasename=result1.getString("Name").toString().trim();
String enteredname=new String(name.getText().trim());
if(enteredname.equals(""))
{
JOptionPane.showMessageDialog(null, "enter name");//valid1 = false;
}
else if(dbasename.equals(enteredname))
{
JOptionPane.showMessageDialog(null, "name taken");//valid1 = false;
name.setText(null);
}
}
//checking email exception
else if(result2.next())
{
String dbaseemail=result2.getString("Email").toString().trim();
String enteredemail=new String(email.getText().trim());
if(enteredemail.equals(""))
{
JOptionPane.showMessageDialog(null, "enter email");//valid1 = false;
}
else if(dbaseemail.equals(enteredemail))
{
JOptionPane.showMessageDialog(null, "email taken");//valid1 = false;
email.setText(null);
}
}
//if no exception is detect exectute the below statement
else
{
PreparedStatement Pstatement=con.prepareStatement("insert into detail values(?,?)");
Pstatement.setString(1,name.getText());
Pstatement.setString(2,email.getText());
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null,"Registered Successfully");
}
statement1.close();
statement2.close();
con.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error during searching");
}
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;
}