The truth is that at the time of development, the database of a web app and a desktop app does not differ.
-
IMPORTANT: before connecting, you must create a BBDD
in MySQL
with its corresponding user and administrator password.
If you do not want to complicate your life use MySQL WorkBench or any other graphical interface
Register the driver on your system ( EYE: the jar has to be in the classpath !!! ):
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver registrado con existo!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("No se ha encontrado el driver en el classpath!", e);
}
Configure the connection to DB:
With MysqlDataSource
(preferred form)
MysqlDataSource dataSource = new MysqlDataSource();
// usuario y pass
dataSource.setUser("usuario");
dataSource.setPassword("password");
// servidor y puerto (he puesto el 3306 que es el std, pero cambialo sino!)
dataSource.setServerName("localhost");
dataSource.setPort(3306);
// base de datos creada
dataSource.setDatabaseName("nombreBBDD");
// crear conexion a partir de los datos
Connection conn = dataSource.getConnection();
Another older way is using DriverManager
:
String URL = "jdbc:mysql:3306//localhost/nombreBBDD";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Once this is done, you can make a query like this:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM TU_TABLA");
// haz cosas con el resultado!
rs.close();
stmt.close();
conn.close();
SOURCES 1 , 2