NadirDev
NadirDev

Reputation: 71

Use MySQL connection in other class Java

I want to use the MySQL connection in an other class. My connection class:

public static Connection connect() {
    Connection con = null;
    String url = "jdbc:mysql://localhost:3306/database";
    String driver = "com.mysql.jdbc.Driver";
    String user = "root";
    String pass = "";
    try {
        Class.forName(driver);
        con = DriverManager.getConnection(url, user, pass);
        if (con == null) {
            System.out.println("Connection cannot be established");
        }
        return con;
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}

In the other class: (just for test)

public static void main(String args[]) throws IOException
{
    MySQL db = new MySQL();
    db.connect();

    db.executeQuery("SELECT VERSION()");


}

It connects successfully to the MySQL server, but in the another class, I can only do db.connect(), and if I execute a Query, it says that the method doesn't exits in the MySQL class.

Upvotes: 0

Views: 2611

Answers (2)

meskobalazs
meskobalazs

Reputation: 16041

db.connect returns a new Connection object, you should store that in a variable, and call executeQuery on it. This, what you posted, should not even compile. And you also should not call a static method as an object method. Make it non-static, or call it statically.

Upvotes: 3

DeepInJava
DeepInJava

Reputation: 1961

basically connect() is a static method . You should call it using class Name like MySQL.connect()

Upvotes: 1

Related Questions