Advertisement
axel08

Untitled

Jan 26th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. package Conect;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.ResultSet;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8.  
  9. public class Conexion1 {
  10.  
  11.  
  12.  
  13.     public static void main(String[] args)
  14.     {
  15.         String driver = "com.mysql.jdbc.Driver";
  16.         String url = "jdbc:mysql://localhost:3306/Empresa";
  17.         String login = "root";
  18.         String password = "studium";
  19.         String sentencia = "SELECT * FROM Clientes";
  20.         Connection connection = null;
  21.         Statement statement = null;
  22.         ResultSet rs = null;
  23.         try
  24.         {
  25.             //Cargar los controladores para el acceso a la BD
  26.             Class.forName(driver);
  27.             //Establecer la conexión con la BD Empresa
  28.             connection = DriverManager.getConnection(url, login, password);
  29.             //Crear una sentencia
  30.             statement = connection.createStatement();
  31.             //Crear un objeto ResultSet para guardar lo obtenido
  32.             //y ejecutar la sentencia SQL
  33.             rs = statement.executeQuery(sentencia);
  34.             while (rs.next())
  35.             {
  36.                 System.out.println(rs.getInt("idCliente") + "-" +
  37.                         rs.getString("nombreCliente"));
  38.             }
  39.         }
  40.         catch (ClassNotFoundException cnfe)
  41.         {
  42.             System.out.println("Error 1-"+cnfe.getMessage());
  43.         }
  44.         catch (SQLException sqle)
  45.         {
  46.             System.out.println("Error 2-"+sqle.getMessage());
  47.         }
  48.         finally
  49.         {
  50.             try
  51.             {
  52.                 if(connection!=null)
  53.                 {
  54.                     connection.close();
  55.                 }
  56.             }
  57.             catch (SQLException e)
  58.             {
  59.                 System.out.println("Error 3-"+e.getMessage());
  60.             }
  61.         }
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement