The update does not apply - java

The update does not apply when i try to change the variable while running the program. It does not have any errors.
It says the update is recorded successfully but it does not apply to Mysql.
Please help!
StaffDA
public void actionPerformedUpdate() {
if (StaffDA.updateCustomer(customer)) {
txtfName.setEditable(false);
txtlName.setEditable(false);
txtGender.setEditable(false);
txtEmail.setEditable(false);
txtDateOfBirth.setEditable(false);
txtUserId.setEditable(false);
txtPassword.setEditable(false);
txtContactNumber.setEditable(false);
txtAddress.setEditable(false);
JOptionPane.showMessageDialog(myFrame,
"Record updated successfully", "Alert",
JOptionPane.INFORMATION_MESSAGE);
}
else {
JOptionPane.showMessageDialog(myFrame,
"Database Error. Record not updated.", "Alert",
JOptionPane.ERROR_MESSAGE);
}
}
StaffUpdatePanel
public static boolean updateCustomer(Customer customer) {
//declare local variables
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 customer SET fName = ?, lName = ?, gender = ?, email = ?, dateOfBirth = ?, userId = ?, password = ? ,contactNumber = ?, address = ? WHERE id = ?";
pstmt = db.getPreparedStatement(dbQuery);
//step 3 - to update record using executeUpdate method
try {
pstmt.setString(1, customer.getfName());
pstmt.setString(2, customer.getlName());
pstmt.setString(3, customer.getGender());
pstmt.setString(4, customer.getEmail());
pstmt.setString(5, customer.getDateOfBirth());
pstmt.setString(6, customer.getUserId());
pstmt.setString(7, customer.getPassword());
pstmt.setString(8, customer.getContactNumber());
pstmt.setString(9, customer.getAddress());
pstmt.setInt(10, customer.getId());
if (pstmt.executeUpdate() == 1)
success = true;
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(success);
//step 4 - close connection
db.terminate();
return success;
}

It could be a problem with the database user's access rights to the database. If you can do a select statement on the database, you could have set the DB user to only have read access.
Also you could try to print out the update statement and run in manually on the database with the same user, to see if the database system itself can run the update correctly, in this case you have narrowed down the problem to the code and not access rights.

Related

java.sql.SQLException: Can not issue executeUpdate() or executeLargeUpdate() for SELECTs

I am trying register page, if email exits already it should get alert message, for this below is my some part of the code, i am using executeQuery for Select query but still i am getting error:
java.sql.SQLException: Can not issue executeUpdate() or executeLargeUpdate() for SELECTs
java code:
Class.forName("com.mysql.jdbc.Driver");
Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/xxxx", "root","root");
PreparedStatement ps=cn.prepareStatement("select * from Register where email=?");
ps.setString(1, email);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
out.println("<script type=\"text/javascript\">");
out.println("alert('Email already Exists Please Try with New Email');");
out.println("location='index.html';");
out.println("</script>");
}
else{
PreparedStatement ps1 = cn.prepareStatement("insert into Register values(?,?,?,?,?)");
ps1.setString(1, name);
ps1.setString(2, email);
ps1.setString(3, mobile);
ps1.setString(4, password);
ps1.setString(5, conform_password);
int i = ps.executeUpdate();
if (i != 0) {
response.sendRedirect("index.html");
} else {
out.println("Some Thing went wrong. Try Again...");
}
}
}
My guess is that the problem has to do with your not closing the first statement used for the select before you try to create another statement for the insert. But, there is a better way to implement your logic, using a single insert:
String sql = "INSERT INTO Register (name, email, mobile, password, confirm_password) ";
sql += "SELECT ?, ?, ?, ?, ? ";
sql += "WHERE NOT EXISTS (SELECT 1 FROM Register WHERE email = ?)";
PreparedStatement ps = cn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, mobile);
ps.setString(4, password);
ps.setString(5, conform_password);
ps.setString(6, email);
int i = ps.executeUpdate();
if (i == 0) {
System.out.println("Email already Exists Please Try with New Email");
}
else {
response.sendRedirect("index.html");
}
If the exists clause of the above insert fails, then nothing should be inserted, and the DML row count returned by executeUpdate() should be zero.

Inserting values into mysql table using jdbc - java application

I am trying to implement a user registration using java and it always returns an error, my user login works fine. But why is this error?
I have implemented a register class which creates the connection and inserts the values. The input validation in done in the actionperformed class.
private boolean register(String username,String email,String password) {
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/erp?" + "user=root&password=");
PreparedStatement sql = (PreparedStatement) conn.prepareStatement("Insert into user(username,email,password) values(? , ?, ?)");
sql.setString(1, username);
sql.setString(2, email);
sql.setString(3, password);
ResultSet rs = sql.executeQuery();
if(rs.next())
return true;
else
return false;
}
catch(Exception e){
e.printStackTrace();
return false;
}
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.getText().length()==0) // Checking for empty field
JOptionPane.showMessageDialog(null, "Insert Username");
else if(jTextField2.getText().length()==0) // Checking for empty field
JOptionPane.showMessageDialog(null, "Insert E-mail address");
else if(jPasswordField1.getText().length()==0) // Checking for empty field
JOptionPane.showMessageDialog(null, "Insert Password");
else if(jPasswordField2.getText().length()==0) // Checking for empty field
JOptionPane.showMessageDialog(null, "Re-enter Password");
else if(!jPasswordField1.getText().equals(jPasswordField2.getText())) // Checking for equal passwords
JOptionPane.showMessageDialog(null, "Password fields do not match");
else{
String user = jTextField1.getText(); // Collecting the input
String email = jTextField2.getText(); // Collecting the input
String pwd = jPasswordField1.getText(); // Collecting the input
//String pwd = pass; // converting from array to string
if(register(user,email,pwd))
JOptionPane.showMessageDialog(null, "Registered Successfully");
else
JOptionPane.showMessageDialog(null, "Error");
}
}
You have problem because you use PreparedStatement executeQuery method. But this method is good for querying database. And for updating database you have to use
PreparedStatement updateQuery method.
Short example:
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "mkyong");
preparedStatement.setString(3, "system");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL stetement
preparedStatement .executeUpdate();
in this question your are mention what type of error you are getting
what ever it should be you just use debugger it will help you to resolve the bug
method executeQuery() is used to retrieve data from DB, like "Select" query/statements but if you want to run "update" ,"delete" or "insert" queries you have to use executeUpdate().use
ResultSet rs = sql.executeUpdate();

How do I send data from 4 text fields to a Derby Database in Netbeans using Java

I have a registration page where information for a customer can be entered into 4 text fields, i.e. Customer name, customer address, customer email and customer contact number.
I was wondering how to get the data from the text fields and into the Derby Database in netbeans using Java.
Well, you need to get the text from the fields first, so as follows:
//Replace the textfield names with your textfield variable names
String customerName = txtFieldCustomerName.getText();
String customerAddress = txtFieldCustomerAddress.getText();
String customerEmail = txtFieldCustomerEmail.getText();
String customerContactNumber = txtFieldCustomerContactNumber.getText();
Now that we have all the data, we can perform a database insert
Connection con = null;
PreparedStatement pstmt = null;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
//Get a connection
con = DriverManager.getConnection("jdbc:derby://localhost:1527/myDB;create=true;user=me;password=mine");//Replace this with your information to your database
//now we have a connection, we can perform the insert
pstmt = con.prepareStatement("insert into TABLE_NAME_HERE (customerName, customerAddress, customerEmail, customerContactNumber) VALUES (?, ?, ?, ?)");
pstmt.prepareString(1, customerName);
pstmt.prepareString(2, customerAddress);
pstmt.prepareString(3, customerEmail);
pstmt.prepareString(4, customerContactNumber);
pstmt.executeUpdate(); //execute the insert
} catch(SQLException sqle) {
sqle.printStackTrace();
}
finally { //close the connection after everything is done.
try {
con.close();
pstmt.close();
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}

Bracket Error in New User Sequence

I Am currently working on a small project for myself which allows me to create new user to a database. Everything was going well until I noticed that one of my brackets on the code is displaying an error. Which is strange due to I checked I closed all of my brackets. If someone could see the missing bracket or help me fix the current ones it would be very useful.
JButton NewUserBtn = new JButton("Create New User");
NewUserBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Username = userText.getText();
String Password = passText.getText();
String Email = emailText.getText();
String cid = cidText.getText();
try {
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT `user_name`, `user_email` FROM `table_1` WHERE `user_name` = ? AND `user_email` = ?");
pst.setString(1, Username);
pst.setString(2, Password);
ResultSet Result = pst.executeQuery();
if (Result.next()) {
JOptionPane.showMessageDialog(null, "Error Account with Infomation already exists.");
}
else {
try {
PreparedStatement pst2 = conn.prepareStatement("INSERT INTO table_1 (user_name, user_pass, user_email, cid)"
+ " VALUES (?, ?, ?, ?)");
pst2.setString(1, Username); //Check Username does not exist!
pst2.setString(2, Password);
pst2.setString(3, Email); //Check Email is not already used!
pst2.setString(4, cid); //Need to add verification that CID is not in use!
pst2.execute();
}
catch (Exception e3) {
e3.printStackTrace();
}
}
}
});
The Bracket is the second to last one. Is says I should add finally but I do not understand why? Thanks for anyone who can solve this problem I'm having.
It's enough to only have one try statement. The code below should be working fine.
try {
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT `user_name`, `user_email` FROM `table_1` WHERE `user_name` = ? AND `user_email` = ?");
pst.setString(1, Username);
pst.setString(2, Password);
ResultSet Result = pst.executeQuery();
if (Result.next()) {
JOptionPane.showMessageDialog(null, "Error Account with Infomation already exists.");
} // if
else {
PreparedStatement pst2 = conn.prepareStatement("INSERT INTO table_1 (user_name, user_pass, user_email, cid)"
+ " VALUES (?, ?, ?, ?)");
pst2.setString(1, Username); //Check Username does not exist!
pst2.setString(2, Password);
pst2.setString(3, Email); //Check Email is not already used!
pst2.setString(4, cid); //Need to add verification that CID is not in use!
pst2.execute();
} // else
} // try
catch (Exception e3) {
e3.printStackTrace();
} // catch
You dont catch or finally your first try block.
You have added try-catch combination to inner try statement just above PreparedStatement, but outer try statement is missing catch or finally. See my comments below:
JButton NewUserBtn = new JButton("Create New User");
NewUserBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String Username = userText.getText();
String Password = passText.getText();
String Email = emailText.getText();
String cid = cidText.getText();
try { //But it doesn't have either catch or finally
Connection conn = DriverManager.getConnection( Host, Name, Pass );
PreparedStatement pst = conn.prepareStatement("SELECT `user_name`, `user_email` FROM `table_1` WHERE `user_name` = ? AND `user_email` = ?");
pst.setString(1, Username);
pst.setString(2, Password);
ResultSet Result = pst.executeQuery();
if (Result.next()) {
JOptionPane.showMessageDialog(null, "Error Account with Infomation already exists.");
}
else {
try { //You have catch for this
PreparedStatement pst2 = conn.prepareStatement("INSERT INTO table_1 (user_name, user_pass, user_email, cid)"
+ " VALUES (?, ?, ?, ?)");
pst2.setString(1, Username); //Check Username does not exist!
pst2.setString(2, Password);
pst2.setString(3, Email); //Check Email is not already used!
pst2.setString(4, cid); //Need to add verification that CID is not in use!
pst2.execute();
}
catch (Exception e3) {
e3.printStackTrace();
}
}
}
});

Updating database from a dynamic jtable

I am trying to update a database from a dynamic JTable. Here is my code
try {
//open connection...
conn = javaConnect.ConnectDb();
//select the qualifications table row for the selected staffID
String sql2 = "select * from QualificationsTable where qualID =" + theRowID;
pStmt = conn.prepareStatement(sql2);
ResultSet rs2 = pStmt.executeQuery();
//check if QualificationsTable has content on that row...
if (rs2.next()) {
//it has content update...
//get the model for the qual table...
DefaultTableModel tModel = (DefaultTableModel) qualTable.getModel();
for (int i = 0; i < tModel.getRowCount(); i++) {
//get inputs from the tables
String qualification = tModel.getValueAt(i, 0).toString();
String yearAttained = tModel.getValueAt(i, 1).toString();
//sql query for updating qualifications table...
String sql3 = "update QualificationsTable set qualifications = ?, yearAttained = ? where qualID = ?";
pStmt = conn.prepareStatement(sql3);
//set the pareameters...
pStmt.setString(1, qualification);
pStmt.setString(2, yearAttained);
pStmt.setInt(3, theRowID);
//execute the prepared statement...
pStmt.execute();
// dbStatement.executeUpdate("INSERT INTO tableName VALUES('"+item+"','"+quant+"','"+unit+"','"+tot+"')");
}
//close connection
conn.close();
JOptionPane.showMessageDialog(null, "Qualifications updated successfully!", "Success", INFORMATION_MESSAGE);
} else {
//it doesnt have content insert...
//get the model for the qual table...
DefaultTableModel tModel = (DefaultTableModel) qualTable.getModel();
for (int i = 0; i < tModel.getRowCount(); i++) {
//System.out.println(tModel.getSelectedColumn()+tModel.getSelectedRow());
//get inputs from the tables
String qualification = tModel.getValueAt(i, 0).toString();
String yearAttained = tModel.getValueAt(i, 1).toString();
//sql query for storing into QualificationsTable
String sql3 = "insert into QualificationsTable (qualifications,yearAttained,qualID) "
+ "values (?,?,?)";
pStmt = conn.prepareStatement(sql3);
//set the parameters...
pStmt.setString(1, qualification);
pStmt.setString(2, yearAttained);
pStmt.setInt(3, theRowID);
//execute the prepared statement...
pStmt.execute();
}
//close connection
conn.close();
JOptionPane.showMessageDialog(null, "Qualifications saved successfully!", "Success", INFORMATION_MESSAGE);
}
} catch (SQLException ex) {
Logger.getLogger(StoreInfo.class.getName()).log(Level.SEVERE, null, ex);
} catch(NullPointerException nfe){
JOptionPane.showMessageDialog(infoParentTab, "Please, always hit the Enter button to effect your changes on the table", "USER ERROR!", ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(infoParentTab, "You must select a Staff from the Browser...", "USER ERROR!", ERROR_MESSAGE);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
what i am actually trying to do is to use a table linked to a database to store qualifications of staff in a company. now each entry in the qualifications database is referenced to the staffID in the staffs database through qualID.
so when i store the qualification on the table, it also records the staff that has the qualification. this should enable me retrieve a particular staff's qualifications from the database when need.
the segment for inserting into the database if empty works fine (i.e. the else... segment). but the update segment (i.e. the if... segment) is faulty in the sense that the code uses the last row on the JTable to populate all the rows in the database table instead of replicating all the new changes into the database table when update is need.
i have tried everything i could to no avail. please i need much help in this...time is not on my side. tnx guys in advance
The best way to do this is to use a CachedRowSet to back up the JTable's model. You'll be able to view, insert and update data easily.
Here's the tutorial: Using JDBC with GUI API

Categories