2010-06-14 178 views
0

我从我的代码中收到cannot find symbol错误。有谁知道什么会导致这个问题?使用Class.forName()时出现“找不到符号”问题()

的代码是:

// Register JDBC driver 
Class.forName("net.sourceforge.jtds.jdbc.Driver"); 

和误差输出为:

blah.java:314: cannot find symbol 
symbol : method forName(java.lang.String) 
location: class java.lang.Class 
       Class.forName("net.sourceforge.jtds.jdbc.Driver"); 
        ^
1 error 

//STEP 1. Import required packages 
import java.sql.*; 

public class JDBCExample { 
    // JDBC driver name and database URL 
    static final String JDBC_DRIVER = "com.sql.jdbc.Driver"; 

    static final String DB_URL = (":jdbc:jtds:sqlserver://localhost:1433/tempdb"); 





    // Database credentials 
    static final String USER = "username"; 
    static final String PASS = "password"; 

    public static void main(String[] args) { 
    Connection conn = null; 
    Statement stmt = null; 
    try{ 
     //STEP 2: Register JDBC driver 
     Class.forName("net.sourceforge.jtds.jdbc.Driver"); 

     //STEP 3: Open a connection 

     System.out.println("Connecting to database..."); 
     conn = DriverManager.getConnection(DB_URL, USER, PASS); 

     //STEP 4: Execute a query 
     System.out.println("Creating database..."); 
     stmt = conn.createStatement(); 

     String sql = "CREATE DATABASE "; 
     stmt.executeUpdate(sql); 
     System.out.println("Database created successfully..."); 
    }catch(SQLException se){ 
     //Handle errors for JDBC 
     se.printStackTrace(); 
    }catch(Exception e){ 
     //Handle errors for Class.forName 
     e.printStackTrace(); 
    }finally{ 
     //finally block used to close resources 
     try{ 
     if(stmt!=null) 
      stmt.close(); 
     }catch(SQLException se2){ 
     }// nothing we can do 
     try{ 
     if(conn!=null) 
      conn.close(); 
     }catch(SQLException se){ 
     se.printStackTrace(); 
     }//end finally try 
    }//end try 
    System.out.println("Goodbye"); 
}//end main 
}//end JDBCExample 
+2

请提出问题,请不要只发布错误消息。 – luke 2010-06-14 03:51:17

+0

@joseph,我试图清理这个问题,使它更加负责任。如果我错误地改变了意图,请告诉我。我猜测你真的在使用GWT吗? – paxdiablo 2010-06-14 04:02:09

+0

@paxdiablo:这个问题已经过度地编辑了。你能否改回它来反映第一个Class.forName ...是代码的事实,并且从method ... onward开始的所有内容都是编译器错误输出? – 2010-06-14 04:51:52

回答

2

其中Class.forName()可以失败不具有上可用的JDBC驱动的主要方法类路径,但这将是一个运行时错误,而不是编译时错误,因为您似乎在这里。

使用我的心理调试能力,我想你可能会使用GWT。我不相信它允许在客户端(它被转换为JavaScript)。所有JDBC的东西都要留在服务器端。 Google自己发布JRE emulation reference,这样你就可以看到允许的内容。

Class支持的方法不限于:

  • desiredAssertionStatus()
  • getEnumConstants()
  • 的getName()
  • getSuperclass之类()
  • IsArray的()
  • isEnum ()
  • isInterface()
  • isPrimitive()
  • 的toString()

如果我说得对,你使用GWT的事实,它可能是最好使用GWT-RPC客户端和服务器之间的交谈,并有服务器本身发出JDBC调用。

如果您需要关于GWT-RPC的更多信息,请参阅here。 GWT新闻组中有一个thread,您可以阅读其中的更多信息。

0

可能出现这样的情况:您在同一个包中有一个名为“Class.java”的类。在这种情况下,它将忽略“Class.java” in java.lang包。由于您未在“Class.java”中实施名为“forName()”的方法,因此会引发此错误。

当我遇到类似的编译时错误时,我想到了它。

相关问题