MySQL异常 - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

时间:2012-07-21 17:04:51

标签: java mysql exception jdbc

我收到错误:

  

'字段列表'中的'未知列'customerno'。

但是,该列存在于我的customer表中。那为什么我得到这个例外?

代码:

import java.sql.*;  

public class Classy {  

    static String myQuery =   
            "SELECT customerno, name" +  
            "FROM customers;";  

    public static void main(String[]args)  
    {  
        String username = "cowboy";  
        String password = "1234567";  
        try  
        {  
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business", username, password);  
            Statement stmt = con.createStatement();  
            ResultSet rs = stmt.executeQuery(myQuery);  

            while(rs.next())  
            {  
                System.out.print(rs.getString("customerno"));  
            }

        } catch(SQLException ex){System.out.println(ex);}  

    }  

}  

3 个答案:

答案 0 :(得分:4)

看看你的查询到底是什么。这样:

static String myQuery =   
        "SELECT customerno, name" +  
        "FROM customers;";  

相当于:

static String myQuery = "SELECT customerno, nameFROM customers;";  

现在你能看到什么是错的吗?我对它抱怨customerno而不是缺少FROM部分感到惊讶......

请注意,我怀疑您不想要;。为了便于阅读,我会把它全部写成一行,当你可以的时候,以及限制可访问性并使其成为最终版本:

private static final String QUERY = "SELECT customerno, name FROM customers";  

答案 1 :(得分:1)

您的语法问题是 nameFROM之间没有空格

String myQuery =   
        "SELECT customerno, name" +  // problem is here
        "FROM customers;"; 

而是在name

之后添加一个空格
 String myQuery =   
        "SELECT customerno, name " +  // add space here
        "FROM customers"; 

答案 2 :(得分:0)

import java.sql.*;  

public class Classy {  

static String myQuery =   
        "SELECT customerno, name" +  
        "FROM customers;";  

public static void main(String[]args)  
{  
    String username = "cowboy";  
    String password = "1234567";  
    try  
    {  
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business", username, password);  
        Statement stmt = con.createStatement();  
        ResultSet rs = stmt.executeQuery(myQuery);  

        while(rs.next())  
        {  

//尝试使用数据库中存在的数值更改此值, 例如,如果它的第2列做了类似的事情 rs.getString(1);

            System.out.print(rs.getString("customerno"));  
        }  


    }catch(SQLException ex){System.out.println(ex);}  

}  

}