Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. DBItem.java
  2.  
  3. package beans;
  4.  
  5. import java.sql.*;
  6. import java.util.*;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9.  
  10. /**
  11. *
  12. * @author elcer
  13. */
  14. public class DBItem {
  15. private String driver = "com.mysql.jdbc.Driver";
  16. private String url = "jdbc:mysql://localhost:3306/items";
  17.  
  18. private Connection conn = null;
  19.  
  20. public DBItem() { //el constructor crea y abre la conexion
  21. try {
  22. Class.forName(driver);
  23. conn = DriverManager.getConnection(url, "usuario", "password");
  24. if (conn != null)
  25. System.out.println("Conexion efectuada con exito");
  26. } catch (ClassNotFoundException | SQLException ex) {
  27. Logger.getLogger
  28. (DBItem.class.getName()).log(Level.SEVERE, null, ex);
  29. }
  30. }
  31.  
  32. public LinkedList<Item> getItems(String tipo) {
  33. LinkedList<Item> itemsTipo = new LinkedList<>();
  34. if (conn != null) {
  35. try (Statement st = conn.createStatement()) {
  36. String sqls = "SELECT * from items WHERE tipo='" + tipo + "'";
  37. try (ResultSet rs = st.executeQuery(sqls)) {
  38. while (rs.next()) {
  39. String nombre = rs.getString("nombre");
  40. Item item = new Item(nombre, tipo);
  41. itemTipo.add(item);
  42. }
  43. }
  44. } catch (SQLException ex) {
  45. Logger.getLogger(DBItem.class.getName()).log(Level.SEVERE, null, ex);
  46. }
  47. }
  48. return itemsTipo;
  49. }
  50.  
  51. public void closeDB() {
  52. try {
  53. conn.close();
  54. } catch (SQLException ex) {
  55. Logger.getLogger(DBItem.class.getName()).log(Level.SEVERE, null, ex);
  56. }
  57. }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement