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;
}
Related
I have tried this so many times but I never did it, this is my code
public static Boolean checkhaveguild(String name) {
try {
Statement statement = connection.createStatement();
PreparedStatement ps = connection.prepareStatement("SELECT * FROM guild");
System.out.println(statement.execute("SELECT * FROM guild WHERE name = "+name+""));
System.out.println("----------");
} catch (SQLException e) {
throw new RuntimeException(e);
}
return false;
}
I am doing a guild plugin on BungeeCord and getting data from MySQL
The code is about checking if the row does not exist and output to boolean
I'd suggest you to learn more about the basics of programming in Java! Minecraft is a great way to start into programming, but you should be interested in doing things properly.
public static boolean hasGuild(String name) {
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
statement = connection.prepareStatement("SELECT COUNT(name) FROM guild WHERE name = ?");
statement.setString(1, name);
resultSet = statement.executeQuery();
if (resultSet.next()) return resultSet.getInt(1) > 0;
} catch (SQLException e) {
// TODO properly handle exception
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO properly handle exception
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO properly handle exception
}
}
}
return false;
}
Some thoughts on what this code is doing:
Asking the database for the number of rows whose name column matches the given string. Always make sure that you only request the data that's necessary for your purpose. Requesting all columns with their data is overkill if you only want to answer if there are any rows or not.
If the number of rows is greater than zero, it'll return true, because there are rows with a matching name column.
Some thoughts you should make yourself:
What is contained in the name column? If it's the guild's name, then that's fine, but if that's the player's name you should consider re-thinking your code. Player's in Minecraft can change their name and hence would lose their guild on your server. Players in Minecraft are uniquely identified by their UUID, which will never change. Maybe consider using the UUID then!
In order for the query to be as fast a possible you should set an INDEX on the name column. That will speed up the lookup proccess even if there are plenty of rows!
Nevertheless: Welcome to StackOverflow! I hope that I could help you and I wish lot's of fun with programming.
in the try, i try sout resultSet and statement before close and it send this to me
resultSet :
com.mysql.cj.jdbc.ClientPreparedStatement: SELECT COUNT(name) FROM guild WHERE name = 'a'
statement :
com.mysql.cj.jdbc.ClientPreparedStatement: SELECT COUNT(name) FROM guild WHERE name = ** NOT SPECIFIED **
and return false is my test at last it will return true if it have if not it will return false
I got a method that deletes a record in the database when inserting a tag value. when a record is deleted, a message in the console screen pops up saying "this record has been deleted ". It works fine when inserting a valid tag value. However, when I insert an invalid tag value that doesn't exist in my database it acts like it has deleted it and displays that previous message. Although within my method says if the outcome is not equal 1 (which is not true) return false, but it's apparently not validating the inserted data. Can anyone tell me what's the problem
public boolean DeleteWallet(String Tag) throws SQLException {
System.out.println("Deleting wallet");
Connection dbConnection = null;
Statement statement = null;
int result = 0;
String query = "DELETE FROM wallets WHERE Tag = '" + Tag + "';";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
System.out.println("The record has been deleted successfully");
// execute SQL query
result = statement.executeUpdate(query);
} finally {
if (statement != null) {
statement.close();
}
if (dbConnection != null) {
dbConnection.close();
}
}
if (result == 1) {
return true;
} else {
return false;
}
}
The statement
System.out.println("The record has been deleted successfully");
is being printed before you actually perform any database operations statement.executeUpdate(query);
Instead, you should perform your database operation within your try statement, then print your success output. If the statement fails (IE an exception is thrown) the success statement will be skipped.
Additionally, instead of relying on the output the the executeUpdate(query) to determine if your query was successful, I would always assume your query or some operation before the query fails, and only return true if all database processing was successful.
Finally, the use of prepared statements will help make your query easier to read, use, and is better secured against SQLInjection attacks.
Example:
public class DatabaseOperations {
public boolean DeleteWallet(String Tag) {
//Query used for prepared statement
static final String DELETE_QUERY = "DELETE FROM wallets WHERE Tag=?";
System.out.println("Attempting to delete wallet using query:" + DELETE_QUERY);
//assume DELETE operation fails due to exection at any stage
Boolean result = false;
try (
//Objects that can automatically be closed at the end of the TRY block
//This is known as AutoCloseable
Connection dbConnection = getDBConnection();
PreparedStatement statment = dbConnection.preparedStatement(DELETE_QUERY))
{
//replace ? with Tag
statement.setString(1, Tag);
int row = preparedStatement.executeUpdate();
//If statement fails skip to catch block
result = true;
System.out.println("The record in row " + row + " has been deleted successfully");
} catch (SQLException sqle) {
//likely thrown due to "Record Not Found"
//TODO investigate further for the specific exception thrown from the database implementation you are using.
//TODO print helpful message to help user of this method resolve this issue
} catch (Exception) {
//TODO handle any other exceptions that may happen
}
return result;
}
}
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");
}
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());
}
I'm trying to delete an event from my table. However I can't seem to get it to work.
My SQL statement is:
public void deleteEvent(String eventName){
String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1";
db.update(query);
System.out.println (query);
}
Using MySQL db
Try using the following :
String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1";
try {
Connection con = getConnection();
Statement s = con.createStatement();
s.execute(query);
} catch (Exception ex) {
ex.printStackTrace();
}
You have to code your getConnection() method to return a valid Database Connection.
I would suggest using Statement.executeUpdate method, since it returns an integer. So after performing this delete query you will also have information if you really deleted any records (in this case you would expect this method to return 1, since you are using LIMIT=1). I would also suggest closing Statement as soon as you don't need it, here is skeleton implementation:
private void performDelete(Connection conn, String deleteQuery, int expectedResult) throws SQLException {
Statement stmt = conn.createStatement();
int result = -1;
try {
result = stmt.executeUpdate(deleteQuery);
if(result != expectedResult) {
//Here you can check the result. Perhaps you don't need this part
throw new IllegalStateException("Develete query did not return expected value");
}
} catch(SQLException e) {
//Good practice if you use loggers - log it here and rethrow upper.
//Or perhaps you don't need to bother in upper layer if the operation
//was successful or not - in such case, just log it and thats it.
throw e;
} finally {
//This should be always used in conjunction with ReultSets.
//It is not 100% necessary here, but it will not hurt
stmt.close();
}
}