Java updating mysql row if id already exists - java

I have a simple form with 5 fields. (txtID, txtFirstName, txtLastName, txtCheque, txtSavings). All I want to do is inserting these fields into my database table "accounts". Before that step I want to check if the ID from my txtID field already exists in my database. If yes then I want to update the database row with the content from the fields. And if not I want to create a new row with the content. So far the check if the ID exists in my DB works but if click on my btn I get the following error message: I dont relly know what I'm doing wrong.
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MariaDB
server version for the right syntax to use near '(LastName,
FirstName,Cheque,Savings) VALUES('Tester','Markus','450.00','50.00" at
line 1
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
String id = txtID.getText();
String checkid ="SELECT * FROM accounts where ID=?";
pst=conn.prepareStatement(checkid);
pst.setString(1, id);
rs = pst.executeQuery();
boolean recordAdded = false;
while(!rs.next()){
recordAdded = true;
}
if(recordAdded){
// the statement for inserting goes here.
}else{
String sql ="UPDATE accounts SET " + "(LastName,FirstName,Cheque,Savings) VALUES" + "(?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1,txtLastName.getText());
pst.setString(2,txtFirstName.getText());
pst.setString(3,txtCheque.getText());
pst.setString(4,txtSavings.getText());
pst.executeUpdate();
getAllAccounts();
JOptionPane.showMessageDialog(null, "Customer Updated");
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
rs.close();
pst.close();
getAllAccounts();
}
catch(Exception e) {
}
}
}

do you let me to make some changes in your code?
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {
try {
String sql = "UPDATE accounts SET LastName = ?, FirstName = ?, Cheque = ?, Savings = ? where id = ?";
pst=conn.prepareStatement(sql);
pst.setString(1,txtLastName.getText());
pst.setString(2,txtFirstName.getText());
pst.setString(3,txtCheque.getText());
pst.setString(4,txtSavings.getText());
pst.setString(5,txtID.getText());
int updatedRowCount = pst.executeUpdate();
// no record with id = txtID
if(updatedRowCount == 0) {
pst.close();
sql = "insert into accounts (ID,LastName,FirstName,Cheque,Savings) values (?,?,?,?,?,?) ";
pst = conn.prepareStatement(sql);
pst.setString(1,txtID.getText());
pst.setString(2,txtLastName.getText());
pst.setString(3,txtFirstName.getText());
pst.setString(4,txtCheque.getText());
pst.setString(5,txtSavings.getText());
pst.executeUpdate();
}
getAllAccounts();
JOptionPane.showMessageDialog(null, updatedRowCount > 0 ? "Customer Updated" : "Customer Inserted");
}
catch(Exception e){
getAllAccounts();
JOptionPane.showMessageDialog(null, e);
}
finally {
try{
pst.close();
}
catch(Exception e) {
}
}
}

Related

Delete from DB in Java

I want to delete a row in DB and it works but here is the problem:
If I enter the value that exists in DB, it is deleted and I get a message "Your Booking is successful canceled"
But also if I enter the value that not exists in DB, I get the same message. Why if the condition does not work?
String sql = "delete from vaccines.patients where idNum = ?";
String res = "Your Booking is successfully canceled";
PreparedStatement state;
try {
state = con.prepareStatement(sql);
state.setString(1, member.getIdNum());
if (member.getIdNum().equals(null)) {
res = "Enter id";
}
state.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
res="Your Booking is not successfully canceled";
}
You must check the number of affected rows instead since an update statement not affecting any rows won't error out.
e.g.
int rowCount = state.executeUpdate();
if (rowCount == 0) {
throw ...;
}

How can I achieve this code?

Hey I have a problem with my java codes. If I enter a text in my IDFiELD and then press the "Enter" And then message come out "ID wasn't recognize, Try again..." but it shows the values in my table. So how can i address that problem.
So here is my code in java eclipse:
IDField.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evnt) {
if (evnt.getKeyCode() == KeyEvent.VK_ENTER) {
try {
String query = "select * from employee where IDNo = ?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, IDField.getText());
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
int count = 0;
while (rs.next()) {
count += 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "ID Verified!");
IDField.setText(null);
} else {
JOptionPane.showMessageDialog(null, "ID was'nt recognize, Try again...");
}
rs.close();
pst.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}
});
I hope you can help me. Thanks.
Your method table.setModel(DbUtils.resultSetToTableModel(rs)); consumes the ResultSet already, so you cannot use it again to count how many results you received.
You can:
run the query twice (simplest to code, but least clean and efficient)
query the table model to see if there are rows
extract the results of the query into a datastructure and convert that to your table model and also use it to check if there were results

how to check if id in mysql already exists with java

I want to check if my id is already exist or not:
sql2 = "SELECT stid FROM student";
stmt.executeUpdate(sql2);
rs = stmt.executeQuery(sql2);
while(rs.next()){
id = rs.getString("stid");
if(tf_insert1.equals(id)){
JOptionPane.showMessageDialog(null, "ID is already exists");
id = tf_insert1.getText();
name = tf_insert2.getText();
address = tf_insert3.getText();
gender = tf_insert4.getText();
ip = tf_insert5.getText();
tf_insert1.setText(id);
tf_insert2.setText(name);
tf_insert3.setText(address);
tf_insert4.setText(gender);
tf_insert5.setText(ip);
Any idea to solve this thing???
Please check this. I have modified code in 2 parts.
One for checking the id exists or not
and another for insert section.
Hope it will help to solve your issue.
private void yourFunction(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"SELECT stid FROM student where stid = ?");
stmt.setLong(1, Long.parseLong(stid.getText()));
ResultSet rs=stmt.executeQuery();
bool recordAdded = false;
while(!rs.next()){
recordAdded = true;
}
if( recordAdded ){
// your code for insertion.
}else{
JOptionPane.showMessageDialog(null, "ID is already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}

check if the record exists in database

I need to check the box no if exist in the database under the remittance id that I enter if the box no exists then i need to show the message that the box no already exists but if it doesn't the it should insert new box i have written some code but its showing error
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(1, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
while(rs.next()){
rs.equals().txtboxno.getText());
}
JOptionPane.showMessageDialog(rootPane, "hello!S");
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
Try this code
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(2, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
bool recordAdded = false;
while(!rs.next()){
/// Do your insertion of new records
recordAdded = true;
}
if( recordAdded ){
JOptionPane.showMessageDialog(rootPane, "Record added");
}else{
JOptionPane.showMessageDialog(rootPane, "Record already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
or you could use a count:
String query = "select count(*)
from dbo.soil_det where rm_id = ? and box_no = ?";
then after executing the query you get the count with
rs.getInt(1)
using that you can decide which info to show to the user
very First You have to get count using sql if count is greater than zero then do not insert records and show message like already exists and in else part insert record. see following example
private boolean findCount(int rm_id,String box_no)
{
int count=0;
//write query here
count = assign query result;
//check count
if(count>0)
{
return false;//records exists
}else{
return true;//records do not exists
}
}
public void insertData()
{
if(findCount(1,"1")){//pass values
//Write down your insert logic
}else{
JOptionPane.showMessageDialog(rootPane, "Records Already Exists");
}
}
Note: Friend in Your Example you have not written the insert logic. only select was there
First you could add -- on the db table -- a unique constrain on the columns (rm_id, box_no), this is anyway a good thing to do.
Then you could simply try to insert the box and catch the exception and check if it is a violation of the unique constraint.
Another option (still keeping the unique constraint) would be to make a more complicated SQL insert statement that inserts only if not existing, you may google "sql insert if not exist" to find some examples...
You need to get the appropriate record from the ResultSet e.g.
boolean found = rs.getString(1).equals().txtboxno.getText());
At the moment you're simply comparing the ResultSet object itself to a string, and that won't work. The above pulls the first record from the ResultSet and performs the comparison on that (note: your datatype may be different and you may need rs.getInt(1) etc.)
Perhaps its sufficient in your case just to check if you have a ResultSet result (via rs.next())
simplified version
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(2, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
if(!rs.next()){
JOptionPane.showMessageDialog(rootPane, "Record added");
}else{
JOptionPane.showMessageDialog(rootPane, "Record already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
rs.next() followed by if condition returns true if the record exists in a table. if not, return false.

How to delete a record (string) JAVA and MYSQL

I successfully can delete an integer but when I tried to make it a STRING it says
"unknown column itemtodelete in where clause but my ITEMTODELETE is a STRING declared in the database not an integer how much It doesn't delete a STRING?
below is my code:
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
int del = (prompt):
if (del == JOptionPane.YES_OPTION){
DelCurRec();
}
}
public void DelCurRec() {
String id = field.getText();
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
try {
Class.forName(connectio);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"JDBC Driver Error",JOptionPane.WARNING_MESSAGE);
}
Statement stmt = null;
Connection con = null;
//Creates connection to database
try {
con = DriverManager.getConnection("Connection");
stmt = con.createStatement();
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Connection Error",JOptionPane.WARNING_MESSAGE);
}
//Execute the SQL statment for deleting records
try {
stmt.executeUpdate(SQL);
//This closes the connection to the database
con.close();
//This closes the dialog
JOptionPane.showMessageDialog(null,"Deleted Succesfully","Delete Successful",JOptionPane.WARNING_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,""+e.getMessage(),"Communication Error",JOptionPane.WARNING_MESSAGE);
}
}
Do NOT use a Statement use a PreparedStatement instead, otherwise your application will be vulnerable to SQL injections. E.g. someone enters a string like: "'; drop table inventory; --"
The corresponding prepared statment would look something like:
String SQL = "DELETE FROM inventory WHERE ItemCode = ? ";
PreparedStatement pstmt = null;
// get a connection and then in your try catch for executing your delete...
pstmt = con.prepareStatement(SQL);
pstmt.setString(1, id);
pstmt.executeUpdate();
try changing the line:
String SQL = "DELETE FROM inventory WHERE ItemCode = "+id+" ";
to
String SQL = "DELETE FROM inventory WHERE ItemCode = '"+id+"' ";
I think you need to pass Integer.parseInt(id) and not id...assuming your id is int
This worked for me:
Statement stmt=con.createStatement();
stmt.executeUpdate("DELETE FROM student WHERE reg_number='R18854';");

Categories

Resources