Guest User

Untitled

a guest
Mar 25th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. public class Item
  2. {
  3. private int id;
  4. private String name;
  5. private int parentId;
  6.  
  7. public Item( )
  8. {
  9.  
  10. }
  11. public Item(int _id,String _name,int _parentId)
  12. {
  13. this.id=_id;
  14. this.name=_name;
  15. this.parentId=_parentId;
  16. }
  17. public int getId() {
  18. return id;
  19. }
  20. public void setId(int id) {
  21. this.id = id;
  22. }
  23. public String getName() {
  24. return name;
  25. }
  26. public void setName(String name) {
  27. this.name = name;
  28. }
  29. public int getParentId() {
  30. return parentId;
  31. }
  32. public void setParentId(int parentId) {
  33. this.parentId = parentId;
  34. }
  35.  
  36. @Override
  37. public String toString() {
  38. return String
  39. .format("Item [id=%s, name=%s, parentId=%s]",
  40. id, name, parentId);
  41. }
  42. }
  43.  
  44. public class ItemDAO
  45. {
  46. private Connection myCon;
  47. public ItemDAO() throws SQLException
  48. {
  49. myCon=DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","root","");
  50. System.out.println("Succesfull connection to database");
  51. }
  52.  
  53. public List<Item> getAllItems() throws SQLException
  54. {
  55. List<Item> list =new ArrayList<>();
  56.  
  57. Statement stmt;
  58. ResultSet result;
  59.  
  60. stmt= myCon.createStatement();
  61. result=stmt.executeQuery("SELECT * FROM items");
  62.  
  63. while(result.next())
  64. {
  65. Item em=convertRowToItem(result);
  66. list.add(em);
  67. }
  68.  
  69. return list;
  70. }
  71. public int rowCount() throws SQLException
  72. {
  73. Statement stmt;
  74. ResultSet rows;
  75. int count=0;
  76. stmt=myCon.createStatement();
  77. rows=stmt.executeQuery("SELECT COUNT(*) FROM items");
  78. while(rows.next())
  79. {
  80. count=rows.getInt(1);
  81. }
  82.  
  83. return count;
  84. }
  85.  
  86. public String getRoot() throws SQLException
  87. {
  88. Statement stmt;
  89. ResultSet row;
  90. String str=null;
  91. stmt=myCon.createStatement();
  92. row=stmt.executeQuery("SELECT * FROM items WHERE parent_id=0");
  93. while(row.next())
  94. {
  95. str=row.getString("name");
  96. }
  97. return str;
  98. }
  99.  
  100. private Item convertRowToItem(ResultSet res) throws SQLException
  101. {
  102. int id=res.getInt("id");
  103. String name=res.getString("name");
  104. int parentId=res.getInt("parent_id");
  105.  
  106.  
  107. Item emp=new Item(id,name,parentId);
  108. return emp;
  109. }
  110. }
Add Comment
Please, Sign In to add comment