Connect java with mysql

0

I have a simple java application, which has 2 options, show the amount of paint cans in the inventory, and show the sum of the prices of all the paint cans, and I have all that data in a simple base of data in MySQL, my question is how can I connect java with MySQL, for when I run my Java program and select option 1, do the corresponding query?

    
asked by darioxlz 15.02.2018 в 02:33
source

2 answers

2

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.

    
answered by 19.02.2018 / 19:18
source
2

Well darioxlz you must use the jdbc that you can download from here link

Once you add the jdbc. The connection is as follows:

package servicios;
import java.sql.*;

public class Conexion {
private static Connection cnx = null;
public static Connection obtener() throws SQLException,  ClassNotFoundException {
  if (cnx == null) {
     try {
        Class.forName("com.mysql.jdbc.Driver");
        cnx = DriverManager.getConnection("jdbc:mysql://localhost/java_mysql", "root", "");
     } catch (SQLException ex) {
        throw new SQLException(ex);
     } catch (ClassNotFoundException ex) {
        throw new ClassCastException(ex.getMessage());
     }
  }
  return cnx;
  }

public static void cerrar() throws SQLException {
  if (cnx != null) {
     cnx.close();
  }
  }
}
    
answered by 15.02.2018 в 03:50