I am trying to delete a row from the database, but the control always goes into the else part below. I tried to execute the same delete statement on the database and it worked there.
I have verified all the column names and the table name are correct.
Can someone guide if I am doing anything wrong here?
Thanks.
public String delAd(String x, String y, String z){
String result = "";
int rowcount = 0;
try{
PreparedStatement ps = con.prepareStatement("DELETE FROM dbname.tablename WHERE iname = ? AND idesc = ? AND seller = ?");
ps.setString(1,x);
ps.setString(2,y);
ps.setString(3,z);
rowcount = ps.executeUpdate();
if(rowcount > 0){
result = "true";
System.out.println("Delete Successful");
}else{
result = "false: Value could not be deleted from the database";
}
}catch(Exception e){
e.printStackTrace();
}
return result;
}
Check in your table if there is any row which satifies the query. simple way to test is do a select statement with the values live below.
SELECT * FROM TABLENAME WHERE INAME='WATEVER' AND IDESC='WATEVER';
it is obvious from the output that there are no rows that are satisfying your query thats why control is jumping to else.
Related
I am trying to make a username only register if that name is not taken, using JDBC connection and checking on SQL Database.
I have the code that checks for the
SELECT * FROM user
WHERE username = 'jessica';
and it finds 2 rows;
Searched a lot and found that with getFetchSize() it would give me the number of rows, and if it finds null it would return 0.
It is always returning 0, I don't know why, because I have the usernames taken twice, it lets me add me always...
https://prnt.sc/galyqo
public int nameAvailable(MyUserApp app, String name) throws SQLException{
String sql = "SELECT * FROM user \n WHERE username = '"+ name +"';";
Statement st = app.getCon().createStatement();
ResultSet rs = st.executeQuery(sql);
int numResults = rs.getFetchSize();
return numResults;
}
This is the register code:
private void RegisterButtonActionPerformed(java.awt.event.ActionEvent evt) {
String username, password, address, dob;
boolean status;
String u;
try {
username = newUsernameField.getText();
password = passwordField2.getText();
address = addressField.getText();
dob = dateofbField.getText();
int no= 5;
if( username.isEmpty() || password.isEmpty() || password.length() < 6 ){
jLabel6.setText("The information you typed in is not valid. ");
status = false;
showTableDB.setText(""+status);
}
else{
no = this.app.nameAvailable(app, username);
jLabel6.setText(no+"");
if(no == 0){
jLabel6.setText("Registered your account, "+username+"!" + no);
status = this.app.registerUser(app, username, password, dob, address);
u = this.app.showInfo(app, username);
showTableDB.setText(u);
no = this.app.nameAvailable(app, username);
}
else{
showTableDB.setText("That username is token. Please choose a different one.");
}
}
} catch (SQLException ex) {
Logger.getLogger(UserAppUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(UserAppUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
Resolved. Solution:
public int getNCount(MyUserApp app, String name) throws SQLException{
String sql = "SELECT COUNT(*) FROM user \n WHERE username = '"+ name +"';";
int rowCount;
PreparedStatement st = app.getCon().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet r = st.executeQuery(sql);
r.next();
// get the number of rows from the result set. On the db it will show a table with "count(*)" and the #counts
rowCount = r.getInt("count(*)");
r.close();
st.close();
return rowCount;
}
By calling these statement on the code:
r.next()
and then
rowCount = r.getInt("count(*)");
I was able to get the 2nd column of the count(*) SQL Statement.
The fetch size is not the same thing as the number of rows. The fetch size is just a way of limiting how many rows at a time will be fetched from the database.
There's no easy way to check the number of rows returned by a select statement. If you really need to know how many rows there are, in the case there's more than one, then one approach would be to iterate through the result set, copying the information that you need from each row into memory; then check the amount of data that you copied at the end.
Alternatively, if you don't actually need any data from the rows themselves, you could try a statement like SELECT count(*) FROM user WHERE username = ?.
One more thing - you need to read about SQL injection attacks. This is where a hacker uses your code to run SQL that they shouldn't. The code you've shown here is vulnerable to an SQL injection attack. But that's another question entirely.
Resolved. Solution:
public int getNCount(MyUserApp app, String name) throws SQLException{
String sql = "SELECT COUNT(*) FROM user \n WHERE username = '"+ name +"';";
int rowCount;
PreparedStatement st = app.getCon().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet r = st.executeQuery(sql);
r.next();
// get the number of rows from the result set. On the db it will show a table with "count(*)" and the #counts
rowCount = r.getInt("count(*)");
r.close();
st.close();
return rowCount;
}
By calling these statement on the code:
r.next()
and then
rowCount = r.getInt("count(*)");
I was able to get the 2nd column of the count(*) SQL Statement.
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 am currently working on a Java project (on NetBeans) and I am struggling with a problem.
In fact, I have a jTable which contains several elements, which element has a jCheckBox in the second column and I would like to make a query to add the selected element (selected by the jCheckBox of course) in a table.
I can get the data that I want to add, but my query works only once. I have already check my loop but I don't where the problem comes from.
I let you see the code :
try {
// Getting id of the selected value in the jComboBox
String idParcours = oParcoursDAO.findIdParcours(jComboBoxParcours.getSelectedItem().toString());
int id = Integer.parseInt(idParcours);
// for each value in the jTable
for(int i=0; i <jTable2.getRowCount(); i++){
boolean isChecked = (Boolean)jTable2.getValueAt(i, 1);
String nomPoi = (String)jTable2.getValueAt(i, 0);
// if the value is selected
if(isChecked){
String IDPoi = oParcoursDAO.findIdPoi(nomPoi);
int idpoi = Integer.parseInt(IDPoi);
System.out.println("idpoi "+idpoi); // It works I saw as idpoi as I have choose
System.out.println("id "+id) // It works too
oParcoursDAO.addPoi(idpoi,id); // it works only once
}
}
}catch (SQLException ex) {
Logger.getLogger(ModificationParcoursJInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
}
Thank you in advance for your help.
This is my statement
public void addPoi(int idPoi,int idParcours) throws SQLException{
String query = "INSERT INTO TB_POI_PARCOURS (id_poi,id_parcours) VALUES (?,?) ";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setInt(1,idPoi);
preparedStatement.setInt(2,idParcours);
preparedStatement.executeUpdate();
preparedStatement.close();
}
Why are you running one query per line? You can execute all of them in a single SQL using batch queries. It will require you to change the code but it will make it more efficient:
public void addPoi(Map<integer,Integer> poiMap) throws SQLException{
String query = "INSERT INTO TB_POI_PARCOURS (id_poi,id_parcours) VALUES (?,?) ";
PreparedStatement preparedStatement = conn.prepareStatement(query);
for(Integer idPoi:poiMap.keySet()) {
preparedStatement.setInt(1,idPoi);
preparedStatement.setInt(2,poiMap.get(idPoi));
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
preparedStatement.close();
}
Of course the original method has to be changed accordingly.
tb_records = jtable name
records = table name inside my database
Date = my first column
hey = substitute for my real password
mydatabase = name of my database
My problem is that, when I highlight a row in my JTable and delete it, it deletes all the rows. I want to delete the selected row only. Here's my code:
int row = tb_records.getSelectedRow();
DefaultTableModel model= (DefaultTableModel)tb_records.getModel();
String selected = model.getValueAt(row, 0).toString();
if (row >= 0) {
model.removeRow(row);
try {
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "hey");
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
ps.executeUpdate();
}
catch (Exception w) {
JOptionPane.showMessageDialog(this, "Connection Error!");
}
}
What could be the problem here? How can I delete a selected row in my database and not all the rows?
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
int row = jTable.getSelectedRow();
String eve = jTable.getModel().getValueAt(row, 0).
String delRow = "delete from user where id="+eve;
try {
ps = myCon.getConnection().prepareStatement(delRow);
ps.execute();
JOptionPane.showMessageDialog(null, "Congratulation !!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
1) Don't display your own message. Display the error message from the Exception as it will give a better explanation what the problem is.
2) Use a proper PreparedStatement for the SQL. You are less likely to make syntax errors. Something like:
String sql = "delete from records where Date= ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, selected );
stmt.executeUpdate();
I don't know much about SQL but maybe you need to pass a Date object not a String object since your where clause is using a Date?
The OP wrote:
SOLUTION: Pick a column with unique values. My Date column has the same values that's why it's deleting all my rows even though I set my row as getSelectedRow. Time_in = my 4th column with unique values.
change
String selected = model.getValueAt(row, 0).toString();
to
String selected = model.getValueAt(row, 3).toString();
and
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
to
PreparedStatement ps = conn.prepareStatement("delete from records where Time_in='"+selected+"' ");
I have two tables. And these tables have the same schema consisting of userid, username. I want to check is there any common username in table1 and table2.
rs1 = statement.executeQuery("select username from table1")
rs2 = statement.executeQuery("select username from table2")
My logic is:
while(rs1.next())
compare the value of rs1 with every value of rs2.
If there match found print one of the value else print both the values.
Is there a way to achieve this in java... Please anyone help me ... Thanks...
I would use a single SQL statement:
select table1.username from table1, table2 where table1.username = table2.username
This will only return usernames that appear in both tables, so no post-processing will be needed.
This construct is called an inner join. If you also want to identify usernames that are unique to table1 and/or table2, you could use an outer join.
You can either solve it through SQL statement IN and NOT IN or you can try something like this:
public boolean compareResultSets(ResultSet resultSet1, ResultSet resultSet2) throws SQLException{
while (resultSet1.next()) {
resultSet2.next();
ResultSetMetaData resultSetMetaData = resultSet1.getMetaData();
int count = resultSetMetaData.getColumnCount();
for (int i = 1; i <= count; i++) {
if (!resultSet1.getObject(i).equals(resultSet2.getObject(i))) {
return false;
}
}
}
return true;
}
Pseudo-Code:
if ( A.type = B.type )
{
PRINT same type
if ( A.format = B.format )
{
PRINT same format
if ( A.value = B.value )
{
PRINT same value
}
else
{
PRINT different value
}
}
else
{
PRINT different format
}
}
else
{
PRINT different type
}
One way could be:-
String query = "(" + query1 +") intersect ("+ query2 + ")";
Where in the intersect operation will anyway give you the common columns.
P.S. :- I know this question is old, but it might help somebody.
I am giving an example to solve this:
rs1 = statement.executeQuery("select username from table1")
rs2 = statement.executeQuery("select username from table2")
while(rs1.next()) {
// Compare till rs1 reachs its last record.
while(rs2.next()) {
if() {
// Do your code here...
}
}
// this will move resultSet cursor to the first position.
rs2.first();
}
This answer is already given by Akash5288 and Edited by Pavel Smirnov. And this worked for me like magic. I don't have access to Like or Comment on the original answer, that's why I am re-posting it. Thanks a lot. Just one edit from my side: rs2.beforeFirst(); will work better than rs2.first();.
I am giving an example to solve this:
rs1 = statement.executeQuery("select username from table1")
rs2 = statement.executeQuery("select username from table2")
while(rs1.next()) {
// Compare till rs1 reachs its last record.
while(rs2.next()) {
if() {
// Do your code here...
}
}
// this will move resultSet cursor to the first position.
rs2.first();
}