sweet dreams
sweet dreams

Reputation: 2134

MySQL exception - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

I get the error:

'Unknown column 'customerno' in 'field list' '.

But, that column exists in my customer table. Then why am I getting this exception ?

Code:

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);}  

    }  

}  

Upvotes: 1

Views: 10423

Answers (3)

John Woo
John Woo

Reputation: 263883

the problem with your syntax is that you have no space between name and FROM

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

instead add a space after name

 String myQuery =   
        "SELECT customerno, name " +  // add space here
        "FROM customers"; 

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503290

Look at what your query really is. This:

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

is equivalent to:

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

Now can you see what's wrong? I'm surprised it complained about customerno rather than the lack of a FROM part...

Note that I suspect you don't want the ; either. I'd write it all one one line just for readability, when you can, as well as limiting the accessibility and making it final:

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

Upvotes: 4

Aaron
Aaron

Reputation: 11693

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())  
        {  

//Try and change this with the numeric value that is present in the database, e.g if it's column 2 do something like rs.getString(1);

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


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

}  

}

Upvotes: 0

Related Questions