Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DatabaseFunctions extends JFrame {
- // This program uses a JTable name jTable to view information from the database
- private DefaultTableModel dataModel;
- private DefaultTableModel checkoutModel;
- private Connection connection;
- public DatabaseFunctions() { // Your constructor
- connect();
- initComponents();
- checkoutModel = (DefaultTableModel) checkoutTable.getModel();
- dataModel = (DefaultTableModel) jTable.getModel();
- populateDataTable("SELECT * FROM TableName");
- }
- private void populateDataTable(String query) {
- // Removes all rows from table
- if (dataModel.getRowCount() > 0) {
- for (int i = dataModel.getRowCount() - 1; i > -1; i--) {
- dataModel.removeRow(i);
- }
- }
- Object rowData[] = new Object[5];
- try {
- connection = ConnectionManager.getInstance().getConnection();
- PreparedStatement preparedStatement
- = connection.prepareStatement(query);
- ResultSet resultSet = preparedStatement.executeQuery();
- while (resultSet.next()) {
- // These are all names of columns of jTable and the database
- rowData[0] = resultSet.getString("Column1");
- rowData[1] = resultSet.getInt("Column2");
- rowData[2] = resultSet.getString("Column3");
- rowData[3] = resultSet.getInt("Column4");
- rowData[4] = resultSet.getInt("Column5");
- dataModel.addRow(rowData);
- }
- } catch (SQLException sqlExcep) {
- sqlExcep.printStackTrace();
- }
- jTable.repaint();
- jTable.revalidate();
- }
- public void connect(){
- String driver = "org.apache.derby.jdbc.EmbeddedDriver";
- String protocol = "jdbc:derby:";
- String databaseName = "usr/database";
- String url = "jdbc:derby://localhost:1527/database ";
- try {
- Class.forName(driver).newInstance();
- connection = DriverManager.getConnection(url, "brinlee", "brinlee");
- System.out.println("Established connection to database");
- }catch (SQLException sqlExcep){
- sqlExcep.printStackTrace();
- displayErrorMessage("Could not establish connection to database \n" +
- "SQL Exception");
- }catch (ClassNotFoundException cnfExcep){
- cnfExcep.printStackTrace();
- displayErrorMessage("Could not establish connection to database \n" +
- "Class Not Found Exception");
- }catch (Exception excep){
- excep.printStackTrace();
- displayErrorMessage("Could not establish connection to database \n" +
- "Exception");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement