Skip to content

Instantly share code, notes, and snippets.

@Elshaman
Created March 7, 2023 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Elshaman/634b1da1dba24e0a70c774091b01d84f to your computer and use it in GitHub Desktop.
Save Elshaman/634b1da1dba24e0a70c774091b01d84f to your computer and use it in GitHub Desktop.
package org.example.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConexionSingleton {
private static String url = "jdbc:mysql://localhost:3306/java_curso";
private static String username="root";
private static String password="";
private static Connection connection;
public static Connection getInstance() throws SQLException {
if(connection==null){
connection = DriverManager.getConnection(url, username, password);
}
return connection;
}
}
package org.example;
import org.example.util.ConexionSingleton;
import java.sql.*;
public class EjemploJdbc {
public static void main(String[] args) {
try (Connection conn = ConexionSingleton.getInstance();
Statement stmt = conn.createStatement();
ResultSet resultado = stmt.executeQuery("SELECT * FROM productos")){
while (resultado.next()){
System.out.println(resultado.getInt("id"));
System.out.println(resultado.getString("nombre"));
System.out.println(resultado.getInt("precio"));
System.out.println(resultado.getDate("fecha_registro"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment