【问题标题】:Mysql syntax exception from jdbc来自 jdbc 的 Mysql 语法异常
【发布时间】:2009-10-24 22:11:56
【问题描述】:

我正在尝试根据以“@localhost”结尾的名称将数据从一个表移动到另一个表,但是在移动数据时我遇到了一个异常: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:你的SQL语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“@localhost”附近使用正确的语法

我用来连接 MySQL 的 JDBC 代码是:

/

/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","");
}
}     

我在 MySQL 中尝试了上述代码的查询变量的值,它工作正常。但为什么不在这里?我正在使用的 MySQL 驱动程序:mysql-connector-java-5.1.5-bin.jar。

【问题讨论】:

    标签: java mysql jdbc


    【解决方案1】:

    你需要引用字符串文字:

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

    您还需要转义字符串s 以防止SQL 注入攻击(或者最好是you should use prepared statements)。

    【讨论】:

      猜你喜欢
      • 2015-12-12
      • 2013-01-15
      • 1970-01-01
      • 2010-11-03
      • 2013-06-04
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      相关资源
      最近更新 更多