Delete from DB in Java - 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 ...;
}

Related

Java updating mysql row if id already exists

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) {
}
}
}

Validating Text fields in Java not working?

I am creating an SQL that stores information about customers, and want all the customers to have unique contact numbers, essentially as an identifier for themselves. However my validation for my SQL seems to run even if the number already exists within the SQL, and am unsure of what is going wrong.
public static boolean uniqueValidation(String contactNum){
Connection c = null;
Statement stmt = null;
boolean result = true;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:custInfo.db"); //this is telling the code where to retrieve the data from that it is looking for.
stmt = c.createStatement();
String sql = "SELECT rowid AS isFound FROM CUSTINFO WHERE CONTACTNUMBER LIKE "+contactNum+""; //collecting a rowid from custinfo, if the number is found anywhere
ResultSet rs = stmt.executeQuery(sql);
String compareString = rs.getString("isFound"); //setting the value from the resultset of rowid to comparestring
if(!compareString.isEmpty()){ //if there is a value return false
result = false;
}else{
result = true; //else return true as there is no value
}
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
return result;
}

How to call the result of a consult and put it in a Textfield? Mysql + Java

my textfield is called pruebamax
With this function I make the connection with the database
public ResultSet getmax() {
ResultSet r = null;
try {
String sql = "select count(*) as Cantidad from tbl_padre";
System.out.println(sql);
Statement st = cx.createStatement();
r = st.executeQuery(sql);
System.out.println(st.executeQuery(sql));
} catch (SQLException ex) {
Logger.getLogger(Tmrptryone.class.getName()).log(Level.SEVERE, null, ex);
}
return r;
}
his method in the event of a button, with this method I want to print in the textfield the data I receive from the database but I got an error.
public void actualizatext() {
try {
ResultSet r = mrp.getmax();
if (r.next()) {
String ID = r.getString("Cantidad");
pruebamax.setText(ID);
}
} catch (SQLException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
Now, I don't know what pruebamax means but the SQL statement you used:
String sql = "SELECT COUNT(*) AS Cantidad FROM tbl_padre";
is specifically used to count the total number of records currently maintained within the specified database table (tbl_padre). The value from that count will be held in the specified temporary field named: Cantidad. When you Use the SQL COUNT statement you are not going to be returned a String data type value. You will be expected to try and acquire a Integer value.
It will not acquire a value from your table ID field as what it looks like you expect.
To properly retrieve the records count from your applied SQL string then it should be used in this fashion:
int count = 0;
try {
String sql = "SELECT COUNT(*) AS rCount FROM tbl_padre";
Statement st = cx.createStatement();
ResultSet r = st.executeQuery(sql);
while (r.next()) {
count = r.getInt("rCount");
}
r.close();
st.close();
// Close your DB connection as well if desired.
// yourConnection.close();
//To apply this value to your JTextField:
pruebamax.setText(String.valueOf(count));
System.out.println("Total number of records in the tbl_padre " +
" table is: " + count);
}
catch (SQLException ex) {
ex.printStackTrace();
}
Try not to use actual table field names for temporary field names.
If you want to be more specific with your count then your SQL statement must be more specific as well. For example, let's assume that we want to count the number of records maintained in our table where a field named Age contains a value which is greater than 30 years old, our sql statement would look like this:
String sql = "SELECT COUNT(*) AS rCount FROM tbl_padre WHERE Age > 30";
You will of course have noticed the use of the SQL WHERE clause.

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 set values from database into the textfield

private void btgetinvActionPerformed(java.awt.event.ActionEvent evt) {
//JOptionPane.showMessageDialog(null, "REMITTANCE ID IS VALID!");
try {
DBUtil util = new DBUtil();
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement("select bk_det.rm_id from bk_det WHERE dbo.bk_det.rm_id = ?");
ResultSet rs;
String rm = tf_rmid.getText().trim();
stmt.setInt(1, Integer.parseInt(rm));
rs = stmt.executeQuery();
while (rs.next()) {
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}
I am actually trying to search value from my database table called dbo.bk_det. I am taking the value of WHERE from my textfield tf_rmid. Everything goes on well without error but once i insert the rm_id and click on button btgetinv it says 123 which is my rm_id is out of range cant understand where the error is and what is the problem.
The problem is with the following statements:
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
The first statement won't work the way you want because there's no column named "box_no" in the select clause. It will throw an exception. Let's assume you change the code to have box_no in the select clause. Then, the second statement will try to retrieve the nth column where the column is the value of box_no. I think you just want:
tfbrname.setText(rs.getString("box_no"));
Again, the above only will work if your SELECT statement includes box_no in the field list.
rs.next() returns false if it does not contain any more records. So if you want to behave something when no records found, you have to check record count.
for example,
int recordCount = 0;
while (rs.next()) {
recordCount++;
int i = Integer.parseInt(rs.getString("box_no"));
tfbrname.setText(rs.getString(i));
}
if(recordCount == 0) {
// do something : report an error or log
}
for further information, see http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#next()

Categories

Resources