0

This is the code I am working with to connect to a mysql database.

I am getting this error: Type mismatch: Cannot convert from java.sql.statement to com.mysql.jdbc.Statement

The line: Statement getData=con.createStatement(); //ERROR HERE

Do I have a class loading issue?

//connect to database

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Date;

import com.mysql.jdbc.Statement; 



public class dbconn {
    public static void main(String args[]) {

        String username = "username";
        String password = "password";
        String url = "jdbc:mysql://localhost:3306/Databasename";

        try {

        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection(url, username, password);
        Statement getData=con.createStatement(); //ERROR HERE
        ResultSet rs = getData.executeQuery("select * from MY_TABLE_NAME");
        while(rs.next())
            System.out.println(rs.getDate(1));
        con.close();

    }catch(Exception e) {System.out.println(e);}


    }


}
1
  • 3
    you should import import java.sql.Statement not com.mysql.jdbc.Statement Commented Oct 29, 2017 at 2:31

1 Answer 1

4

This statement:

 Statement getData = con.createStatement();

won't compile because the signature of createStatement() says that it returns a java.sql.Statement. But you have imported com.mysql.jdbc.Statement, and that means that Statement means com.mysql.jdbc.Statement.

Solutions:

  1. Fix the import statement (preferred!!).
  2. Cast the returned value to Statement. This kind of works, but you are doing an unnecessary runtime type-check (that could fail!) AND the code will break if you change your JDBC driver to some other vendor's.

Lessons:

  1. Don't blindly accept your IDE's suggestions / completions for imports. They may be incorrect.
  2. If you are designing an API yourself, avoid the temptation of picking a class or interface name that is the same one used in the Java SE class libraries.
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.