2012-07-21 83 views
1

我得到的錯誤:MySQL的例外 - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

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

但是,在我的客戶表中存在的列。那爲什麼我會得到這個異常?

代碼:

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

    } 

} 

回答

1

與你的語法問題是你有name和之間沒有空格FROM

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

name

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

感謝,而不是添加一個空格!我不知道這種事情不會由API本身處理。 – 2012-07-21 17:28:14

+0

@sweetdreams:它怎麼可能?你剛剛得到了一個*字符串* - 如何知道當你寫「nameFROM」時,你的意思是「name FROM」?這是要求一點點的API ... – 2012-07-21 21:54:21

+0

是啊...我的笨:( – 2012-07-21 22:01:47

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

//嘗試與數值存在於數據庫中更改此, e.g如果它是第2列做類似 rs.getString(1);

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


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

} 

} 
3

看看你的查詢真的是什麼。這:

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"; 
相關問題