I have a problem in validating my delete query anything I type even if the data is not on my database it keeps deleting it says success I want it to have an error if the user type a data that is not exists in the database. Here's my code:
try{
System.out.println("Enter record you want to delete: ");
frail = scn.nextLine();
}catch(Exception ee){
System.out.println(ee.getMessage());
}
try{
stmt = conn.createStatement();
String sqlII = "delete from tbl_test where test_name = ?";
PreparedStatement psII = conn.prepareStatement(sqlII);
psII.setString(1, frail);
psII.executeUpdate();
int rowAffacted = psII.executeUpdate();
if (rowAffacted != 0) {
System.out.println("Deleted!");
}else{
System.out.println("No Affected Rows!");
}
}
catch(Exception eer){
System.out.println(eer.getMessage());
}
psII.executeUpdate(); returns an int. If these value is zero, no lines are delete, so you can see that the user exists is not in the database and you can show an error. Is the user is corect, the value should be grater than zero.
int noOfAffectedRows =psII.executeUpdate();
if (noOfAffectedRows = 0){
//show Error
}
You could catch the return value of executeUpdate as below:
int rowAffacted = psII.executeUpdate();
if (rowAffacted != 0) {
System.out.println("Deleted!");
}
Javadoc for executeUpdate's return value says
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
executeUpdate() returns the number of rows altered or returns 0 in case no rows are affected, so in your case you can do something like:
int alteredRows=psII.executeUpdate();
if(alteredRows==0)
{
System.out.println("No rows deleted");
}
else
{
System.out.println(alteredRows +"rows deleted");
}
Related
I would like to use same result set twice, once is to check whether it is empty and execute code based on the result, and then, using (resultset.next() the second result set will always skip a line because of the first result set
Here's my code so far :
connection = DriverManager.getConnection(connection);
statement = (Statement) connection.createStatement();
resultset = statement.executeQuery(query);
String id = "0";
String idfromdb;
if(resultset.next() == false){
System.out.println("table is empty")
statement.executeUpdate(" INSERT INTO table VALUES ('value') ");
}
else{
while(resultset.next()){
idfromdb = resultset.getString("value")
if(! idfromdb = id){
System.out.println("no similar data has been found");
}
else{
System.out.println("similar data has been found");
}
}
}
When you call resultset.next() it will fetch one record,so you need to call previous() to reset the cursor
The full code:
boolean hasRecord = true;
if(!resultset.next()){// you are missing ) here
System.out.println("table is empty")
statement.executeUpdate(" INSERT INTO table VALUES ('value') ");
hasRecord = false;
}
if(hasRecord){
resultset.previous();//move to the previous record
}
Change to do-while loop:
if(resultset.next() == false{
System.out.println("table is empty")
statement.executeUpdate(" INSERT INTO table VALUES ('value') ");
} else {
do {
idfromdb = resultset.getString("value")
if(! idfromdb = id){
System.out.println("no similar data has been found");
}
else{
System.out.println("similar data has been found");
}
} while(resultset.next());
}
do-while evaluates its expression at the bottom of the loop instead of the top.
I am trying to compare a specific value from the values returned by database.
I am getting multiple rows from STORESTAFF but I am trying to compare one of the values returned from the table..
contains() and
equals()
are not working.
String qry = "Select all employe_id from storestaff where post='Admin'";
pstmnt = conn.prepareStatement(qry);
ResultSet rs2 = pstmnt.executeQuery(qry);
if (rs2.next()) {
String aa = rs2.getString("employe_id");
if (aa.contains(UN.getText())) {
this.aa = aa;
JOptionPane.showMessageDialog(null, "Exists");
} else {
JOptionPane.showMessageDialog(null, "Username doesn't Exist");
}
}
Can anyone suggestt me a better solution for it or can tell me the better solution for it?
If you use if it will return the first values, in your case you have to use while, which loop throw all the results, so you can check multiple results, instead you can use :
boolean check = false;
while (rs2.next()) {
String aa = rs2.getString("employe_id");
if (aa.contains(UN.getText())) {
this.aa = aa;
check = true;//if the value exist change the variable to true
break; //and break the loop
}
}
//when you end you have to check the value, if true then the user exist else no
if (check) {
JOptionPane.showMessageDialog(null, "Exists");
} else {
JOptionPane.showMessageDialog(null, "Username doesn't Exist");
}
Change if(rs2.next()) to while(rs2.next()) You are getting bulk data, so you need to iterate over it to compare one of the value which you want
I wanted an error to popup, when the user entered a wrong id into the delete field. But even if a wrong id is entered, the query still proceeds, but no data is deleted. Here's my code:
String value = jTextField19.getText();
if (value == null || "".equals(value)) {
JOptionPane.showMessageDialog(null, "The field is blank!");
} else {
theQuery("DELETE FROM inventorydb WHERE item_id=('"+jTextField19.getText()+"') AND item_id IS NOT NULL");
}
The theQuery method:
private void theQuery(String query) {
Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory", "root", "");
st = con.createStatement();
st.executeUpdate(query);
JOptionPane.showMessageDialog(null, "Done!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Error!");
}
}
First of all: do not ever directly build SQL queries from user input, use prepared statements instead. If you don't know about SQL Injection, you should.
If you are using JDBC, you can check the result of #executeUpdate() to see how many rows were affected. If it was zero, then you can say that it was a wrong id.
This is the method definition:
public int executeUpdate(java.lang.String sql)
The return value is:
An int that indicates the number of rows affected, or 0 if using a DDL statement.
In the program at hand, you can just simply do this:
int deleted = st.executeUpdate(query);
if (deleted == 0) {
JOptionPane.showMessageDialog(null, "Nothing to delete!");
return;
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String del_user = JOptionPane.showInputDialog(null,"Enter the Username To be deleted :" ,"Delete User !", JOptionPane.WARNING_MESSAGE);
try {
stmt = con.createStatement();
String quer = "delete from Udet where username='"+del_user+"'";
rs=stmt.executeQuery(quer);
int count=0;
while(rs.next())
{
count++;
}
if(count==1)
{
JOptionPane.showMessageDialog(null,"The user has been deleted");
}
else
{
JOptionPane.showMessageDialog(null,"No such User Exists");
}
} catch(Exception e){}
}
THE QUERY EXECUTES FINE ! THE RECORD GETS DELETED BUT THE LINES AFTER QUERYEXECUTION ARE NOT EXECUTING ...
the JOptionPane will work after the try block but then the value of count wont be determined...
A DELETE statement doesn't return a ResultSet and therefore you should use the method stmt.executeUpdate(quer); instead of stmt.executeQuery(quer);.
One way you can see how many results were deleted from the query is run a SELECT COUNT(*) query on the table before and after the DELETE using the executeQuery() method which will both times return a ResultSet with a single result containing how many records the table contains. After running it before and after the DELETE you can compare the 2 numbers.
The result will probably be a String but you can just use int integer = Integer.parseInt(String); to get the int from it. The code should look like this:
stmt = "SELECT COUNT(*) AS Count FROM table_name";
int initialSize = 0;
rs = stmt.executeQuery(stmt);
while(rs.next){
initialSize = Integer.parseInt(rs.getString("Count");
}
Run the DELETE query and then repeat the COUNT query passing the int into a new variable (for this answer I'll call it newSize) so the number of changes the DELETE made would be:
int changesMade = initialSize - newSize;
I want to check whether the newly entered data is already in the table
code:
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
Error :
Exception:java.sql.SQLException: Illegal operation on empty result set.
You need to check if the result set has elements or not:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
You get this exception when the select statement returns an empty set. Add a try/catch block which acts upon the knowledge that the data is not already in the table in the catch block.
You need to check the ResultSet first to check to see that it contains rows:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
The easiest way to check whether a particular record exists in the database might be just as follows:
Select 1 from bank where No = [your_supplied_value]
This query would return 1 if it finds a row in your database with the supplied data or return an empty resultset. So, all you need to check is whether ANY value is returned in the resultset or whether it is emtpy.
Here's a sample code to get you started:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
I hope this is not your final code, because there're several problems with it:
You're not managing your resources properly. Once you're done querying your database, you should consider closing your resultset, statement and connection objects.
Note that I checked whether the text in the JTextField is empty or not. This is a good way of preventing a call to the database when you know that the text field had no value in it.
I would suggest using a PreparedStatement rather than a Statement for querying to your database.
A ResultSet is initially positioned before the first row. So you need to call next() to move it to the next row (and check that it returns true) before you call one of the getXXX() methods.
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}