Kirty Bhushan
Kirty Bhushan

Reputation: 147

Can i concatenate my String containing data with a mysql Query?

I have this code portion as :

String t = (tname2.getText());
     String h = (value2.getText());

     PreparedStatement ps ;

     if(h.length()>2)
     {
         ps = con.prepareStatement("DELETE FROM "+t+" where empname = "+ h);
         //ps.setString(2,h);
         ps.executeUpdate();
           JOptionPane.showMessageDialog(null, "Record deleted !", "Confirmation", JOptionPane.INFORMATION_MESSAGE);
     }

Now, the line ps = con.prepareStatement("DELETE FROM "+t+" where empname = "+ h); isn't working . It works the other way around using "?". As like "Delete * from "+ t +" where empname =?"; and then setting the value of empname. I wanna know , if there's a way i can do things using concatenation of my empname with the query?? Can someone provide a few hints please?? `

Upvotes: 1

Views: 1292

Answers (2)

Biber
Biber

Reputation: 727

You are missing properly opening and closing double quotes:

Try this:

ps = con.prepareStatement("DELETE FROM " + t + " where empname = '" + h + "'");

Upvotes: 0

Ye Win
Ye Win

Reputation: 2098

Use PreparedStatement with a parametrized query and set the value.
This using will also prevent SQL injection.
Because concatenate values into your query make vulnerable to SQL injection.

eg.

ps = con.prepareStatement("DELETE FROM "+t+" where empname = ?");
psmt.setString(1, h);

Upvotes: 5

Related Questions