Advertisement
Guest User

Untitled

a guest
Jul 14th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.28 KB | None | 0 0
  1. import java.sql.*;
  2.  
  3. public class ConnJDBC {
  4. final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
  5. final static String DB_URL = "jdbc:mysql://localhost/DRAFT";
  6.  
  7. final static String USER = "user";
  8. final static String PASS = "pass";
  9.  
  10. public static void main(String[] args) {
  11. Connection conn = null;
  12. Statement stmt = null;
  13.  
  14. try {
  15. Class.forName(JDBC_DRIVER); // registrar driver JDBC
  16. conn = DriverManager.getConnection(DB_URL, USER, PASS); // abrir la conexion
  17. stmt = conn.createStatement();
  18. String sql = "SELECT nombre FROM empleados";
  19. ResultSet rs = stmt.executeQuery(sql);
  20.  
  21. while (rs.next()) {
  22. String nombre = rs.getString("nombre");
  23. System.out.println(nombre);
  24. }
  25.  
  26. rs.close();
  27. stmt.close();
  28. conn.close();
  29.  
  30. } catch (SQLException e) { // errores JDBC
  31. e.printStackTrace();
  32. } catch (Exception e) { // otros errores, como de Class.forName
  33. e.printStackTrace();
  34. } finally {
  35. try {
  36. if (stmt != null)
  37. stmt.close();
  38. } catch (SQLException e) {
  39. // aca no se puede hacer nada
  40. }
  41.  
  42. try {
  43. if (conn != null)
  44. conn.close();
  45. } catch (SQLException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement