Guest User

Untitled

a guest
Apr 22nd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. package Model;
  2.  
  3. import java.awt.*;
  4. import java.sql.*;
  5. import java.util.*;
  6. import javax.swing.*;
  7.  
  8.  
  9. public class TableFromDatabase extends JFrame
  10. {
  11. public TableFromDatabase()
  12. {
  13. Vector columnNames = new Vector();
  14. Vector data = new Vector();
  15.  
  16. try
  17. {
  18.  
  19. // Verbinding met database
  20.  
  21. String driver = "com.mysql.jdbc.Driver";
  22. String url = "jdbc:mysql://localhost/project-registratie";
  23. String userid = "root";
  24. String password = "";
  25.  
  26. Class.forName("com.mysql.jdbc.Driver").newInstance();
  27. Connection connection = DriverManager.getConnection( url, userid, password );
  28.  
  29. // data uit tabel lezen
  30.  
  31. String sql = "Select * from project";
  32. Statement stmt = connection.createStatement();
  33. ResultSet rs = stmt.executeQuery( sql );
  34. ResultSetMetaData md = rs.getMetaData();
  35. int columns = md.getColumnCount();
  36.  
  37. // column namen ophalen.
  38.  
  39. for (int i = 1; i <= columns; i++)
  40. {
  41. columnNames.addElement( md.getColumnName(i) );
  42. }
  43.  
  44. // row data ophalen
  45.  
  46. while (rs.next())
  47. {
  48. Vector row = new Vector(columns);
  49.  
  50. for (int i = 1; i <= columns; i++)
  51. {
  52. row.addElement( rs.getObject(i) );
  53. }
  54.  
  55. data.addElement( row );
  56. }
  57.  
  58. rs.close();
  59. stmt.close();
  60. connection.close();
  61. }
  62. catch(Exception e)
  63. {
  64. System.out.println( e );
  65. }
  66.  
  67. // tabel maken + informatie van database er in zetten
  68.  
  69. JTable table = new JTable(data, columnNames)
  70. {
  71. @Override
  72. public Class getColumnClass(int column)
  73. {
  74. for (int row = 0; row < getRowCount(); row++)
  75. {
  76. Object o = getValueAt(row, column);
  77.  
  78. if (o != null)
  79. {
  80. return o.getClass();
  81. }
  82. }
  83.  
  84. return Object.class;
  85. }
  86. };
  87.  
  88. JScrollPane scrollPane = new JScrollPane( table );
  89. getContentPane().add( scrollPane );
  90.  
  91.  
  92.  
  93. JPanel buttonPanel = new JPanel();
  94. getContentPane().add( buttonPanel, BorderLayout.SOUTH );
  95.  
  96.  
  97. }
  98.  
  99. }
Add Comment
Please, Sign In to add comment