To connect Java with MySQL is easy, you just have to follow some simple steps.
Step 1.
You need the JDBC driver from MySQL. You can download it at the following link here . If you are using Windows, be sure to download the version that is in ZIP.
Step 2.
You must add the JDBC that is a .jar
file to your project, that is, to the Build-Path of your project. If you are using Eclipse, you can add the file by right-clicking on the name of your Project > Build Path > Configure Build Path . In the Libraries tab, click Add Jars if the file was copied to your project folder or Add External JARs if you have the file in another directory on your computer. Then, you click on the lower button that says Apply and Close.
Step 3. You must create a class with a distinctive name, example ConexionMySQL
.
This class will look like this (I have commented on each line for you to understand):
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConexionMySQL {
// Librería de MySQL
public String driver = "com.mysql.jdbc.Driver";
// Nombre de la base de datos
public String database = "databasemovies";
// Host
public String hostname = "localhost";
// Puerto
public String port = "3306";
// Ruta de nuestra base de datos (desactivamos el uso de SSL con "?useSSL=false")
public String url = "jdbc:mysql://" + hostname + ":" + port + "/" + database + "?useSSL=false";
// Nombre de usuario
public String username = "root";
// Clave de usuario
public String password = "123456789";
public Connection conectarMySQL() {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
}
Step 4. Another class where you will do INSERT, UPDATE, DELETE, etc ...
For example, we have a class called Insertar
, in it you will have the following:
// Instancias la clase que hemos creado anteriormente
private ConexionMySQL SQL = new ConexionMySQL();
// Llamas al método que tiene la clase y te devuelve una conexión
private Connection conn = SQL.conectarMySQL();
// Query que usarás para hacer lo que necesites
private String sSQL = "";
Example, how do I make INSERT ?. You must use this:
// Query
sSQL = "INSERT INTO USERS (first_name, last_name) VALUES (?, ?)";
// PreparedStatement
PreparedStatement pstm = conn.prepareStatement(sSQL);
You just need the rest of the necessary code corresponding to the PreparedStatement
to correctly insert the data into the database, which is another issue that has no place in your question.
I hope I have helped you.