In part 3 of this series, we finished discussing the final points of using a database in our java programs. Now we will incorporate everything into one class that we can include in any program we write.
First off, we will create a package for our databaseconnector class that can easily be imported by our future programs. We also need to import the JDBC package and create our class. We are also going to want global variables in which to store our Connection and Statement objects.
package databaseconnector;
import java.sql.*;
public class DatabaseConnector {
Connection mysqlConn = null;
Statement stat = null;
The next step is to create a constructor to bring in the information we need to create a connection to the database. From Part 1, we know that we need the location of the database, username, password, and database name. In order to simplify the connection process, we can also go ahead and create our database url. Our constructor should look something like this.
public DatabaseConnector
(String username, String password,
String databaseName, String mysqlServer)
{
String databaseURL = “jdbc:mysql://” + mysqlServer +
“:3306/” + databaseName;
createConnection(databaseURL, username, password);
}
Next step (obviously) is to create the createConnection() function that is called in our constructor. This function will create our database connection and also the statement we will use for the majority of our queries.
private void createConnection
(String databaseURL, String username, String password)
{
try {
Class.forName(“com.mysql.jdbc.Driver”).newInstance();
mysqlConn = DriverManger.getConnection
(databaseURL, username, password);
stat = mysqlConn.createStatement();
} catch (Exception e) {
System.err.println(“Unable to connect to database”);
}
}
Now that we have a database connection we are ready to write the functions to send queries through that connection. Look for this and more in part 5 of this series.
Pingback: 7 Thailand Turning Sites | Full Moon Party Thailand