tags:

views:

126

answers:

2

I'm trying to move the data from one table to another based on names which end with "@localhost", but while moving the data I'm getting an exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@localhost' at line 1

The JDBC code which I've used to connect with MySQL is:

/

/package foo;
import javax.sql.*;
import java.sql.*;

public class TablesUpdate
{

public static String MoveMessage(String s)
{
int count=0;
try{
String query="insert into deadletter(message_name,repository_name,message_state,error_message,sender,recipients,remote_host,remote_addr,message_body,message_attributes,last_updated) select message_name,repository_name,message_state,error_message,sender,recipients,remote_host,remote_addr,message_body,message_attributes,last_updated from inbox where sender="+s+"@localhost;";
Connection con=databaseConnection();
Statement stmt=con.createStatement();

 count=stmt.executeUpdate(query);
}
 catch(Exception e)
{
e.printStackTrace();
}
if(count>0)
return "Data has been moved";
else
return "There is no data";


}

public static void main(String[] args)
{
TablesUpdate.MoveMessage(args[0]);
}


public static Connection databaseConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
      return DriverManager.getConnection("jdbc:mysql://localhost:3306/mail","root","");
}
}

I tried the value of query variable of above code in MySQL, and it worked correctly. But why not here? MySQL driver I'm using: mysql-connector-java-5.1.5-bin.jar.

+3  A: 

You need to quote the string literal:

where sender='"+s+"@localhost';

You also need to escape the string s to prevent SQL injection attacks (or preferably, you should use prepared statements).

James McNellis
A: 

After solving the above problem(special thanks to James), I'm getting another bug saying: mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraint.Violation.Exception:Duplicate entry 'red-Mail1254659472250-0' for key 'PRIMARY'.

I really don't get it, what's that above bug mean?

NewMember
Ask as a new question.
OMG Ponies