Does connecting to a java database have to be by a main class only?

Asked

Viewed 74 times

-2

To make a connection to the java database, I only have to do it through a main class or I can do it through another class??

public class ConexaoBasica {

    public static void main(String[] args) throws SQLException {
        Connection conexao = DriverManager.getConnection("banco", "root", "");
        System.out.println(conexao);
        System.out.println("Conectado!!!");     
        conexao.close();
    }
}

1 answer

1


No need, the recommended is to leave it in a separate class and make an instance of it or make a static method to recover the connection, follow a class example with a method for connection in the database.

public class SqlConnection
{
    public static Connection connect() {
        Class.forName("com.mysql.jdbc.Driver");  
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/teste","teste","teste");  

        return con;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.