Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation error - com.mysql.jdbc.Driver cannot be resolved to a variable

Tags:

java

eclipse

jdbc

I am barely familiar with pre-bundled STS. I am trying out JDBC for MySQL in Eclipse/Spring on Fedora 17

Downloaded the mysql JDBC drivers (mysql-connector-java-5.1.22-bin.jar). Then in the IDE

  1. Created a project and named it JDBC
  2. Created a folder called 'lib' under the project
  3. Went to Project > Properties . Selected the Java Build Path, then selected the 'Libraries' tab. clicked on 'Add Jars' Selected JDBC > lib > mysql---.jar and clicked OK. This added under the Project Explorer pane a 'Referenced Libraries', under which I see the mysql jar file.
  4. Wrote the following code under the project

I kind of thought I had done what was needed to compile. However, I am seeing

Class.forName(com.mysql.jdbc.Driver);

com.mysql.jdbc.Driver cannot be resolved to a variable

Can you tell me what's wrong here.

    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;


    public class TestJDBC {

        /**
         * @param args
         */
        public static void main(String[] args)  throws Exception{
            // TODO Auto-generated method stub
            Connection connection = null;
            Statement statement = null;
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                Class.forName(com.mysql.jdbc.Driver);
                connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb?" + 
                             "user=myuser&password=mypwd");
                if (connection != null) {
                    System.out.println ("Connected may be?");
                    connection.close();
                }
                else {
                    System.out.println ("Not connected?");
                }
            }
            catch (Exception e) {
                connection.close();
            }
        }
    }
like image 533
rpat Avatar asked Dec 02 '12 15:12

rpat


2 Answers

Class.forName("com.mysql.jdbc.Driver");

or

Class.forName(com.mysql.jdbc.Driver.class.getName());

will work better. (The 2nd one compiles but doesn't really make sense cause it assumes that class is already loaded :)

like image 165
mazaneicha Avatar answered Sep 22 '22 06:09

mazaneicha


You want to use:

Class.forName("com.mysql.jdbc.Driver");

In the future, note that the compiler was telling you what it was expecting: a variable. You just have to figure out how to modify or convert what you have into what it wants. In this case, anything that converts to a value (a constant, a variable or a method returning a value) can be used.

like image 28
Chris Gerken Avatar answered Sep 22 '22 06:09

Chris Gerken