sql在简单查询中抛出错误

时间:2015-10-09 20:22:57

标签: java mysql sql-server jdbc

所以我得到了一个通过JDBC连接到数据库的Java应用程序。我现在要做的是从数据库中获取与Java Apllication中的输入匹配的特定条目。

public String getA(String tablename, String input){
String result = null;
try {
    String query = ("select * from " +tablename+ " where name = "+input);
    rs = stt.executeQuery(query);
    while (rs.next()){
        String rsh = rs.getString("Name");
        result = rsh; 
    }
    } catch (Exception acc_ex){
        System.out.println("Acces excpetion in .getA: "+acc_ex);
        return null; 
    } finally {
        return result; 
    }
}

投掷:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column '[input-here]' in 'where clause'

其他方法中的查询工作得很好,以相同的方式构造它们。 我有什么想法可以解决这个问题吗? 感谢

2 个答案:

答案 0 :(得分:4)

此代码行input中的字符串值("select * from " +tablename+ " where name = "+input);应该有单引号。

例如,如果您的tablename是SomeTable,并且您的输入值是SomeNameValue,那么现在写入MySql的查询将是......

select * from SomeTable where name = SomeNameValue

这是错误的,它应该是这样的,用单引号围绕值......

select * from SomeTable where name = 'SomeNameValue'

所以我提到的代码行将改为此...

String query = ("select * from " +tablename+ " where name = '" +input+ "'");

答案 1 :(得分:0)

请在输入前后添加单引号:

String query = ("select * from " + tablename + " where name = '" + input + "'");