Reputation: 11
I'm getting the cannot find symbol
error from my code. Does anyone know what can cause this problem?
The code is:
// Register JDBC driver
Class.forName("net.sourceforge.jtds.jdbc.Driver");
and the error output is:
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
Upvotes: 0
Views: 5592
Reputation: 102
There can be a scenario where you have a class named "Class.java" in the same package. In that case it ignores the "Class.java" in java.lang package. Since you didn't implement a method called "forName()" in your "Class.java", it throws this error.
It occurred to me when I got a similar compile-time error.
Upvotes: 0
Reputation: 881113
The main way in which Class.forName()
can fail is not having the JDBC drivers available on the class path but that would be a run-time error, not a compile-time error as you seem to be getting here.
Using my powers of psychic debugging, I think you may be using GWT. I don't believe it allows that on the client side (where it's converted to JavaScript). All JDBC stuff has to stay on the server side. Google themselves publish the JRE emulation reference so you can see what is allowed.
The supported methods of Class
are limited to:
If I am right about the fact you're using GWT, it's probably best to use GWT-RPC to talk between the client and server, and have the server itself issue JDBC calls.
If you want further information on GWT-RPC, see here. There's a thread in the GWT news group which you can read for further information.
Upvotes: 3