SlideShare a Scribd company logo
DBConnectionPane.java
/*
* This class defines an extension of BorderPane that allows the user to select
* or enter a JDBC driver and a database URL, plus a username and password.
* The pane establishes a connection to that driver and URL when its Connect to
* DB button is clicked, unless there are errors. If the user later changes the
* connection, the previous connection is closed and a new one established; if
* an error occurs, the previous connection is closed and the connection
* property is set to null.
*
* The driver input combo box only offers the MySQL driver. Oracle has removed
* the JDBC-ODBC bridge driver from Java 8, and the online Oracle database
* access doesn't work for me; the page won't load.
*
* Author: Bill Rutherford
*
*/
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.geometry.*;
import java.sql.*;
public class DBConnectionPane extends BorderPane {
/** Database connection object */
private Connection connection;
// UI input controls
private Label lblStatus = new Label();
private ComboBox<String> cboDriver = new ComboBox<>();
private ComboBox<String> cboDatabaseURL = new ComboBox<>();
private TextField tfUsername = new TextField();
private PasswordField pfPassword = new PasswordField();
public DBConnectionPane() {
// Set up the combo boxes
cboDriver.getItems().add("com.mysql.jdbc.Driver");
cboDriver.setEditable(true);
cboDatabaseURL.getItems().addAll("jdbc:mysql://localhost/javabook",
"jdbc:mysql://localhost/test");
cboDatabaseURL.setEditable(true);
// Create UI
HBox labelPane = new HBox();
labelPane.setPadding(new Insets(5, 10, 10, 10));
labelPane.getChildren().add(lblStatus);
GridPane inputPane = new GridPane();
inputPane.setPadding(new Insets(0, 10, 0, 10));
inputPane.setHgap(10);
inputPane.setVgap(10);
inputPane.add(new Label("JDBC Drive"), 0, 0);
inputPane.add(cboDriver, 1, 0);
inputPane.add(new Label("Database URL"), 0, 1);
inputPane.add(cboDatabaseURL, 1, 1);
inputPane.add(new Label("Username"), 0, 2);
inputPane.add(tfUsername, 1, 2);
inputPane.add(new Label("Password"), 0, 3);
inputPane.add(pfPassword, 1, 3);
Button btConnect = new Button("Connect to DB");
HBox buttonPane = new HBox();
buttonPane.setPadding(new Insets(0, 10, 10, 10));
buttonPane.setAlignment(Pos.CENTER_RIGHT);
buttonPane.getChildren().add(btConnect);
setTop(labelPane);
setCenter(inputPane);
setBottom(buttonPane);
// Set button event handler
btConnect.setOnAction(e -> connectToDB());
}
// Create DB connection object and return it in the connection property
private void connectToDB() {
try {
if (connection != null) { // A previous connection was established
connection.close();
connection = null;
}
Class.forName(cboDriver.getValue()); // Load the driver
String databaseURL = cboDatabaseURL.getValue();
connection = DriverManager.getConnection(databaseURL,
tfUsername.getText(), pfPassword.getText());
lblStatus.setText("Connected to " + databaseURL);
}
catch (NullPointerException ex) {
lblStatus.setText("Please enter a driver name");
}
catch (ClassNotFoundException ex) {
lblStatus.setText("Invalid driver name, or driver not installed");
}
catch (SQLException ex) {
if (ex.getMessage().contains("Access denied"))
lblStatus.setText("Invalid username/password combination");
else if (ex.getMessage().contains("No suitable driver found"))
lblStatus.setText("Invalid database URL");
else if (ex.getMessage().contains("The url cannot be null"))
lblStatus.setText("Please enter a database URL");
else if (ex.getMessage().contains("Unknown database"))
lblStatus.setText(ex.getMessage());
else {
lblStatus.setText("Unexpected error");
ex.printStackTrace();
}
}
}
/** Return connection property */
public Connection getConnection() {
return connection;
}
}
TestDBConnectionPane.java
/*
* This program defines a DBConnectionPane class that extends BorderPane, and
* tests it. The test program displays two windows - the test window as the
* primary stage, and the DBConnectionPane window off to the left as a secondary
* stage. The test window uses the connection defined in the connection window
* to obtain and show the tables in the database when its Show Database Tables
* button is clicked.
*
* Author: Bill Rutherford
*
*/
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.geometry.Pos;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import java.sql.*;
public class TestDBConnectionPane extends Application {
private TextArea taTables = new TextArea();
@Override
public void start(Stage primaryStage) {
// Create connection pane
DBConnectionPane dbPane = new DBConnectionPane();
// Create UI for test window
Button btShowTables = new Button("Show Database Tables");
HBox buttonPane = new HBox(10);
buttonPane.setAlignment(Pos.CENTER);
buttonPane.getChildren().add(btShowTables);
taTables.setEditable(false);
taTables.setWrapText(true);
VBox testPane = new VBox(10);
testPane.getChildren().addAll(taTables, buttonPane);
// Set button event handler
btShowTables.setOnAction(e -> showDatabaseTables(dbPane));
// Set up the test pane in the primary stage and show it
Scene testScene = new Scene(testPane, 300, 150);
primaryStage.setTitle("Test DBConnectionPane");
primaryStage.setScene(testScene);
primaryStage.show();
// Create a secondary stage, set up the connection pane in it, and show
// it off to the left of the test window
Stage secondaryStage = new Stage();
Scene dbScene = new Scene(dbPane, 320, 210);
secondaryStage.setTitle("DB Connection");
secondaryStage.setScene(dbScene);
secondaryStage.setX(primaryStage.getX() - 350);
secondaryStage.setY(primaryStage.getY() - 30);
secondaryStage.show();
}
// Obtain and show the table names in the database
private void showDatabaseTables(DBConnectionPane dbPane) {
Connection connection = dbPane.getConnection();
String tables = "";
try {
DatabaseMetaData dbMetaData = connection.getMetaData();
ResultSet rsTables = dbMetaData.getTables(null, null, null,
new String[] {"TABLE"});
while (rsTables.next())
tables += (rsTables.getString("TABLE_NAME") + " ");
if (tables.equals(""))
taTables.setText("No tables in database");
else
taTables.setText(tables);
}
catch (NullPointerException ex) {
taTables.setText("Error: No connection established");
}
catch (SQLException ex) {
taTables.setText("Unexpected error");
ex.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}

More Related Content

ODP
Box connector Mule ESB Integration
PDF
OpenDMS - the first 2 weeks
PDF
Mule caching strategy with redis cache
PDF
Refreshing mule cache using oracle database change notification
PDF
SQLite in Adobe AIR
ODP
Msql
PDF
Spring 4 - A&BP CC
PDF
DBD::SQLite
Box connector Mule ESB Integration
OpenDMS - the first 2 weeks
Mule caching strategy with redis cache
Refreshing mule cache using oracle database change notification
SQLite in Adobe AIR
Msql
Spring 4 - A&BP CC
DBD::SQLite

What's hot (20)

PDF
How to execute an oracle stored procedure with nested table as a parameter fr...
PPT
Jsp/Servlet
PPT
JavaScript
PPT
Synapse india reviews on php and sql
DOCX
Mule with jdbc(my sql)
DOCX
Java beans
PPS
Jdbc example program with access and MySql
PPT
Php with MYSQL Database
PDF
the Spring 4 update
PDF
Jsp standard tag_library
DOC
Library Project
PDF
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
DOC
Plsql
PDF
Introduction to php database connectivity
PDF
Teste de Integração com DbUnit e jIntegrity
PDF
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
PDF
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
ODP
Database Connection With Mysql
PDF
Java Web Programming Using Cloud Platform: Module 3
PDF
4.3 MySQL + PHP
How to execute an oracle stored procedure with nested table as a parameter fr...
Jsp/Servlet
JavaScript
Synapse india reviews on php and sql
Mule with jdbc(my sql)
Java beans
Jdbc example program with access and MySql
Php with MYSQL Database
the Spring 4 update
Jsp standard tag_library
Library Project
#36.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_재직자환급교육,실업자교육,국비지원교육, 자바교육,구...
Plsql
Introduction to php database connectivity
Teste de Integração com DbUnit e jIntegrity
#18.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_국비지원IT학원/실업자/재직자환급교육/자바/스프링/...
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
Database Connection With Mysql
Java Web Programming Using Cloud Platform: Module 3
4.3 MySQL + PHP
Ad

Similar to Database Connection Pane (20)

PPT
jdbc_presentation.ppt
PPT
PPT
Java database connectivity with MYSQL
PDF
I am looking for some assistance with SQLite database. I have tried se.pdf
PPTX
Getting Started with React v16
PDF
Tomcat连接池配置方法V2.1
DOCX
Java database connecticity steps
PDF
知っておきたいSpring Batch Tips
PPT
4. Database Connectivity using JDBC .ppt
DOCX
Accessing data with android cursors
DOCX
Accessing data with android cursors
PDF
Java Web Programming [3/9] : Servlet Advanced
PDF
Play 2.0
PDF
Deeply Declarative Data Pipelines
PPTX
Detail view in distributed technologies
PPTX
React outbox
PDF
Create a Java FX GUI program that allows the user to insert data int.pdf
PDF
Lecture17
PDF
NoSQL and JavaScript: a Love Story
jdbc_presentation.ppt
Java database connectivity with MYSQL
I am looking for some assistance with SQLite database. I have tried se.pdf
Getting Started with React v16
Tomcat连接池配置方法V2.1
Java database connecticity steps
知っておきたいSpring Batch Tips
4. Database Connectivity using JDBC .ppt
Accessing data with android cursors
Accessing data with android cursors
Java Web Programming [3/9] : Servlet Advanced
Play 2.0
Deeply Declarative Data Pipelines
Detail view in distributed technologies
React outbox
Create a Java FX GUI program that allows the user to insert data int.pdf
Lecture17
NoSQL and JavaScript: a Love Story
Ad

Database Connection Pane

  • 1. DBConnectionPane.java /* * This class defines an extension of BorderPane that allows the user to select * or enter a JDBC driver and a database URL, plus a username and password. * The pane establishes a connection to that driver and URL when its Connect to * DB button is clicked, unless there are errors. If the user later changes the * connection, the previous connection is closed and a new one established; if * an error occurs, the previous connection is closed and the connection * property is set to null. * * The driver input combo box only offers the MySQL driver. Oracle has removed * the JDBC-ODBC bridge driver from Java 8, and the online Oracle database * access doesn't work for me; the page won't load. * * Author: Bill Rutherford * */ import javafx.scene.layout.*; import javafx.scene.control.*; import javafx.geometry.*; import java.sql.*; public class DBConnectionPane extends BorderPane { /** Database connection object */ private Connection connection; // UI input controls private Label lblStatus = new Label(); private ComboBox<String> cboDriver = new ComboBox<>(); private ComboBox<String> cboDatabaseURL = new ComboBox<>(); private TextField tfUsername = new TextField(); private PasswordField pfPassword = new PasswordField(); public DBConnectionPane() { // Set up the combo boxes cboDriver.getItems().add("com.mysql.jdbc.Driver"); cboDriver.setEditable(true); cboDatabaseURL.getItems().addAll("jdbc:mysql://localhost/javabook", "jdbc:mysql://localhost/test"); cboDatabaseURL.setEditable(true); // Create UI HBox labelPane = new HBox(); labelPane.setPadding(new Insets(5, 10, 10, 10)); labelPane.getChildren().add(lblStatus); GridPane inputPane = new GridPane(); inputPane.setPadding(new Insets(0, 10, 0, 10)); inputPane.setHgap(10); inputPane.setVgap(10); inputPane.add(new Label("JDBC Drive"), 0, 0); inputPane.add(cboDriver, 1, 0); inputPane.add(new Label("Database URL"), 0, 1); inputPane.add(cboDatabaseURL, 1, 1); inputPane.add(new Label("Username"), 0, 2); inputPane.add(tfUsername, 1, 2); inputPane.add(new Label("Password"), 0, 3); inputPane.add(pfPassword, 1, 3); Button btConnect = new Button("Connect to DB"); HBox buttonPane = new HBox(); buttonPane.setPadding(new Insets(0, 10, 10, 10)); buttonPane.setAlignment(Pos.CENTER_RIGHT); buttonPane.getChildren().add(btConnect);
  • 2. setTop(labelPane); setCenter(inputPane); setBottom(buttonPane); // Set button event handler btConnect.setOnAction(e -> connectToDB()); } // Create DB connection object and return it in the connection property private void connectToDB() { try { if (connection != null) { // A previous connection was established connection.close(); connection = null; } Class.forName(cboDriver.getValue()); // Load the driver String databaseURL = cboDatabaseURL.getValue(); connection = DriverManager.getConnection(databaseURL, tfUsername.getText(), pfPassword.getText()); lblStatus.setText("Connected to " + databaseURL); } catch (NullPointerException ex) { lblStatus.setText("Please enter a driver name"); } catch (ClassNotFoundException ex) { lblStatus.setText("Invalid driver name, or driver not installed"); } catch (SQLException ex) { if (ex.getMessage().contains("Access denied")) lblStatus.setText("Invalid username/password combination"); else if (ex.getMessage().contains("No suitable driver found")) lblStatus.setText("Invalid database URL"); else if (ex.getMessage().contains("The url cannot be null")) lblStatus.setText("Please enter a database URL"); else if (ex.getMessage().contains("Unknown database")) lblStatus.setText(ex.getMessage()); else { lblStatus.setText("Unexpected error"); ex.printStackTrace(); } } } /** Return connection property */ public Connection getConnection() { return connection; } } TestDBConnectionPane.java /* * This program defines a DBConnectionPane class that extends BorderPane, and * tests it. The test program displays two windows - the test window as the * primary stage, and the DBConnectionPane window off to the left as a secondary * stage. The test window uses the connection defined in the connection window * to obtain and show the tables in the database when its Show Database Tables * button is clicked. * * Author: Bill Rutherford * */
  • 3. import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.geometry.Pos; import javafx.scene.layout.*; import javafx.scene.control.*; import java.sql.*; public class TestDBConnectionPane extends Application { private TextArea taTables = new TextArea(); @Override public void start(Stage primaryStage) { // Create connection pane DBConnectionPane dbPane = new DBConnectionPane(); // Create UI for test window Button btShowTables = new Button("Show Database Tables"); HBox buttonPane = new HBox(10); buttonPane.setAlignment(Pos.CENTER); buttonPane.getChildren().add(btShowTables); taTables.setEditable(false); taTables.setWrapText(true); VBox testPane = new VBox(10); testPane.getChildren().addAll(taTables, buttonPane); // Set button event handler btShowTables.setOnAction(e -> showDatabaseTables(dbPane)); // Set up the test pane in the primary stage and show it Scene testScene = new Scene(testPane, 300, 150); primaryStage.setTitle("Test DBConnectionPane"); primaryStage.setScene(testScene); primaryStage.show(); // Create a secondary stage, set up the connection pane in it, and show // it off to the left of the test window Stage secondaryStage = new Stage(); Scene dbScene = new Scene(dbPane, 320, 210); secondaryStage.setTitle("DB Connection"); secondaryStage.setScene(dbScene); secondaryStage.setX(primaryStage.getX() - 350); secondaryStage.setY(primaryStage.getY() - 30); secondaryStage.show(); } // Obtain and show the table names in the database private void showDatabaseTables(DBConnectionPane dbPane) { Connection connection = dbPane.getConnection(); String tables = ""; try { DatabaseMetaData dbMetaData = connection.getMetaData(); ResultSet rsTables = dbMetaData.getTables(null, null, null, new String[] {"TABLE"}); while (rsTables.next()) tables += (rsTables.getString("TABLE_NAME") + " "); if (tables.equals("")) taTables.setText("No tables in database"); else taTables.setText(tables); }
  • 4. catch (NullPointerException ex) { taTables.setText("Error: No connection established"); } catch (SQLException ex) { taTables.setText("Unexpected error"); ex.printStackTrace(); } } public static void main(String[] args) { launch(args); } }