Created
March 7, 2023 15:07
-
-
Save Elshaman/634b1da1dba24e0a70c774091b01d84f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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