0

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.

0

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.