The perfect online platform for artists and freelancers

Whether it be traveling, making music, or writing, everyone has a passion for something that they love. So why not share that passion with the rest of the world? Freelance Frontier is unlike any other content sharing site out there. Most websites allow you to share your content for their own profit. At Freelance Frontier we believe that the users are the ones doing the work and therefore deserve a share of the profit. Getting started is easy and free. We hope to see your content soon!

Build a Portfolio

Build your online portfolio. Share your posts, resume, education and more to stand out. Integrate external media such as Facebook and LinkedIn to showcase even more about yourself.

Robust Services

Users can enjoy a wide variety of free services such as audience geolocation, published work reports, in-app messaging and more. Stay in the loop with other freelancers like yourself.

Fast & Simple

Getting started is easy and free. Instantly begin uploading your work and track how it performs against a variety of metrics. Easy to use tools allow you to quickly extract the information you want.

Notifications

Receive push notifications on your dashboard to get alerted to things that matter. Stay on top of important events such as messages from potential clients, employers, post performance and a whole lot more.

If We Win, Our Users Win


Earn a percentage of the organization's revenue share based on metrics such as your post like count, comment count and more. We will keep all users notified of when the organization will be able to make payments. One-third of the organization's revenue will always be allocated for our freelancers. We will always be investing in ways to grow the organization and provide more free services to our great community.


Stripe Payments through the Freelance Frontier
Freelance Frontier Mobile Mockup

Mobile Friendly

Publish content or analyze your audience on the go with our responsive UI. Connect with like minded entrepreneurs from across the globe. Keep a lookout for the mobile app. For more info, get in touch with us today.

Freelance Frontier iPad Mockup

An Introduction to Java Database Connectivity (JDBC)

by Matt Daronco | 2016-02-07

Views Today: 2
Views All Time: 1588
Likes: 10
Comments: 0
An Introduction to Java Database Connectivity (JDBC)

        In order to scale software applications that require very large amounts of memory, database administration languages such as SQL and MongoDB ought to be incorporated, since they alleviate heavy storage loads off of the main client-server chain (as opposed to more localized storage methods such as hash tables). These technologies allow data to be accessed via some configured server-side transaction, such as the Java programming language. Sun Microsystems (now Oracle) created an application programming interface in order to specify how a higher level language such as Java could interact with a consolidated database in a timely and efficient fashion. Sun Microsystems (1990's at the time) also specified how a Java database connectivity diver (JDBC) ought to perform. In short, a database driver allows a server-side application to connect to a database in order to exchange data. Thus, as long as a database driver is available for a given database management system (DBMS), the Java programmer will be able to perform data transactions with it.

Four Major JDBC Driver Categories

  1. Type 1 JDBC to ODBC Driver

            This driver converts the Java JDBC application programming interface (API) to Microsoft's Open Database Connection (ODBC) driver. Note that the extra translation step from one API to the other may take a toll on performance.

  2. Type 2 Java/Native Code Driver

            This driver is code-specific per DBMS, thus sacrificing portability for nativity.

  3. Type 3 JDBC Driver

            Referred to as the Java Protocol and is the most widely used JDBC driver.

  4. Type 4 JDBC Driver

            Known as the Type 4 Database Protocol, this driver allows SQL queries to be translated into any data format required by the DBMS.

        Perhaps the most straightforward way to begin performing database transaction with Java is to simply use the standard JDBC API, which is defined in the java.sql package and its extension, the javax.sql package. These packages contain classes that allow you define compatible data objects with any applicable DBMS. Here are 5 generic steps you will find yourself going through when establishing connection with a database:

  1. Load the JDBC Driver

            This basically informs the Java run-time environment which JDBC driver the program is using. Use Class.forName() to specify the JDBC driver by passing as a string argument as such:

    
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // loads the JDBC-ODBC bridge
                            
  2. Connect to Your DBMS

            Once the driver is loaded, you can establish the connection to the database from your server by using the DriverManager.getConnection() method. This method returns a Database interface that will be responsible for communication between the server and the database. It takes the URL to the database as a String parameter, along with a String UserID and String password (note that the Connection instance is declared as private).

    Establishing a Database Connection Using String Credentials (incomplete program)

    
    String URL_DB = "jdbc:odbc:EmployeeInformation"; // String path to the database table containing employee information
    String User_ID = 'mpd';
    String Password = "secret";
    private Connection connection; // make the class instance private so it's un-accessible outside of the class (security purposes)
    
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        connection = DriverManager.getConnection(URL_DB, User_ID, Password); // now the connection is set up and data transactions may begin
                            
  3. Generate and Execute an SQL Statement

            Now that the connection to the database has been established via the driver, you can prepare an SQL statement to execute. You can do this by generating an instance of the Statement member class of the java.sql package. While writing this process, note that we need to use Java exceptions in order to handle the bad transactions.

    Executing an SQL Statement (incomplete program)

    
    String URL_DB = "jdbc:odbc:EmployeeInformation";
    String User_ID = 'mpd';
    String Password = "secret";
    Statement request; // declare an object of the Statement class
    ResultSet rows;
    
        try { // database transactions can fail or timeout while bytes are
              // being transmitted in between the server and the database, so we need
              // to handle the error case.
              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                connection = DriverManager.getConnection(URL_DB, User_ID, Password); // variables that we created in the last code snippet
        } catch (SQLException e) {
            System.out.println("An error occurred while communicating with the database: " + e)
        }
    
        // now we create the query that SQL will use to retrieve blocks of data from the database (the data type is a String)
        String query = "SELECT * FROM EmployeeInformation WHERE ID != 5";
        req = connection.createStatement(); // call the createStatement() method on the 'connection' object
        rows = req.executeQuery(query); // finally, call the execute() method on tbe 'req' object
                            

            Note above how we call an instance of the ResultSet class. This object will be used to store the resulting rows from our SQL queries. We can choose to process the rows data object on the server or on the client side. If we choose to do the latter, we can encode the rows data set to a more browser friendly format such as JSON or XML. In the latter case, we could easily convert the ResultSet object rows into JSON using the Convertor class defined here on Github by Andrew Zakordonets (which ties in the next step).

  4. Process Data Returned by the DBMS

            As we pointed at above, there are several free and open source resources that anyone can use to encode query results into any necessary data format. Below is an example where we encode the query results from the DBMS to an XML format using the Java XMLEncoder class, as defined in the Oracle Documentation (see more on handling files in Java if you are unfamiliar with the BufferedOutputStream class):

    Assume we have a file called output.xml off of the root directory, to which we will write the XML encoded output of the database query

    
    import java.beans.Encoder;
    import java.lang.Object;
    
    // remember that in Java pointers are kept hidden by their parent objects.  Thus, passing a ResultSet object here as a
    // parameter of the WriteXMLObject() passes along the unique memory address of the object as well
    
    public static void WriteXMLObject(ResultSet set, String outputFile) {
            XMLEncoder encoder = new XMLEncoder(BufferedOutputStream(
                new FileOutputStream("output.xml")));
            encoder.writeObject(set);
            encoder.close(); // close the encoder port for re-use
    }
                            

            The example code above will translate an object of the class ResultSet (taken as the first parameter) and output its structure in XML. You could, of course, simply desire to output the contents off the ResultSet object directly using Java's getString() method, which is defined in the java.lang.String class. See an example below where we iterate over our Object[] array using java.lang.* methods:

    
    // ...
    
    String query = "SELECT * FROM EmployeeInformation WHERE ID != 5";
    req = connection.createStatement();
    rows = req.executeQuery(query);
    
    String EmployeeName;
    double EmployeeSalary;
    int EmployeeAge;
    
    String PrintRow;
    boolean records = rows.Next();
    if (!records) {
        System.out.println("Sorry, no data was returned from the database.");
    } else {
        do {
            EmployeeName = rows.getString('Name'); // Assume this column name was called 'Name' in the SQL table
            EmployeeSalary = rows.getDouble('Salary');
            EmployeeAge = rows.getInt('Age');
    
            System.out.println("Employee Name: " + EmployeeName);
            System.out.println("Employee Salary: $" + Double.toString(EmployeeSalary));
            System.out.println("Employee Age: " + Integer.toString(EmployeeAge));
        } while (results.Next()); // the Next() method returns a boolean value
    }
                            

            The program above may connect to a database with the following table structure:

    ID [INT] EmployeeName [VARCHAR(30)] EmployeeSalary [FLOAT] EmployeeAge [INT]
    1 John Doe 65000.00 25
    2 Laura Lang 70000.00 32
  5. Close the Connection to the Database

            After we are performing our desired data transactions, we need to close our connection to the database using the close() method as such:

    
    connection.close(); // close the connection to terminate the instance of the Connection class
                            

Click to Take Quiz

Test Yourself!

        There are several other child classes of the java.sql package, and therefore much more functionality available than described here. For more information on Java database connectivity or similar topics, don't hesitate to contact us.

No recent articles to show.
1.  
Using Command Line Package Managers

Matt Daronco - 2016-01-21

  Programming

2.  
You'll Never Be Without - EP

Nathan Turner - 2016-01-20

  Music & Video

3.  
Implementing a Hash Table in C++

Matt Daronco - 2016-01-16

  Programming

4.  
5.  
9 Things You Should Know About Go

Matt Daronco - 2016-01-25

  Programming

6.  
What is Data Binding?

Matt Daronco - 2016-01-30

  Programming

7.  
Implementing Binary Trees in C

Matt Daronco - 2016-01-22

  Programming

10.  
Using Arrays in Java

Matt Daronco - 2016-02-09

  Programming

11.  
Class Inheritance in Java

Matt Daronco - 2016-02-22

  Programming

12.  
1.  
Using Component Diagrams in Visual Paradigm UML

Matt Daronco - 2016-03-10

Views today: 8

  Programming

2.  
Cathedral Cove in the Coromandel Peninsula of New Zealand

Kendra Kubo - 2016-05-11

Views today: 8

  Photography

3.  
An Introduction to JSON

Matt Daronco - 2016-02-02

Views today: 7

  Programming

4.  
Implementing a Hash Table in C++

Matt Daronco - 2016-01-16

Views today: 6

  Programming

6.  
Creating a Search Engine with PHP and jQuery

Matt Daronco - 2016-01-15

Views today: 5

  Programming

7.  
An Introduction to Bootstrap

Matt Daronco - 2016-01-26

Views today: 5

  Programming

8.  
Stack vs Heap Memory

Matt Daronco - 2016-01-28

Views today: 5

  Programming

9.  
What are Methods in Java?

Matt Daronco - 2016-02-19

Views today: 5

  Programming

10.  
12.  
Understanding the Client-Server Model of Computing

Matt Daronco - 2016-01-16

Views today: 4

  Programming

Go Pro Shots

(swipe up on mobile to close after enlarging)