Creating a MySQL Connection Class in Java
Creating a MySQL Connection Class in Java
When I started learning Java, one of the first tasks was connecting to a MySQL database. To achieve this, it is common practice to create a class responsible for centralizing the connection configuration and providing Connection objects to the rest of the application.
Basic Example
package com.egga.appvet.includes;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
public class ConexionBD {
private static final String URL = "jdbc:mysql://localhost:3306/AppVet";
private static final String USER = "tuusuario";
private static final String PASS = "tupassword@";
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASS);
}
}
In this example, three constants are defined:
- URL: the MySQL database address.
- USER: the username used to connect to the server.
- PASS: the password for the user.
The getConnection() method returns a Connection instance, allowing other classes to perform queries, inserts, updates, or deletes.
One advantage of this approach is that the connection configuration is centralized in a single place. If the server, database name, or credentials change, you only need to modify this class without affecting the rest of the application.
In modern versions of Java, the MySQL JDBC driver is automatically registered when the application starts, so it is usually not necessary to use Class.forName(), which was common in older versions.
Using the Connection Class
Once the ConexionBD class is created, it can be used from other classes to interact with the database.
Suppose we want to retrieve a list of pets stored in the mascotas table. We can create a class that uses the connection provided by ConexionBD.
package com.egga.appvet.mascotas;
import com.egga.appvet.includes.ConexionBD;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ListarMascotas {
public void listar() {
String sql = "SELECT idmascota, nombre FROM mascotas";
try (Connection conn = ConexionBD.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
System.out.println(
rs.getInt("idmascota") + " - " +
rs.getString("nombre")
);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Comments
Post a Comment