NEWS: Total Picture Views: 147060 | Total Article Views: 155600 | Top 5 Most Popular Article: 1. Am I Stuck Algorithm with Becker Robot | 2. How to read a JSON and work with it | 3. PickUpThings with Becker Robot | 4. Encrypted Data GUI (Download .Zip) | 5. Create Wall and Things with Becker

How to create and use Database Connection Java Web

Description:

In this article. I'll be showing you how to connect to a database and use the Connection.

Code:

public class ConnectionControl {
    static Connection connection = null;
    private static Connection connect(){

        String driverName="com.mysql.jdbc.Driver";
        String dbUrl="jdbc:mysql://localhost:3306/Database_Name";
        String userName="username";
        String password="password";

        try {
            try {
                Class.forName(driverName).newInstance();
            } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
                e.printStackTrace();
            }
            connection = DriverManager.getConnection(dbUrl, userName, password);
            return connection;
        } catch (SQLException e) {
            System.out.println("SQL Error: " + e);
            return null;
        }
    }
    public static Connection getConnection(){
        if(connection != null)
            return connection;
        else{
            connection = connect();
            return connection;
        }
    }
}


/**** To use the connection in an external Class ***********/
Connection myConnection = ConnectionControl.getConnection();
Attachments: None

Tags: JDBC Connection J2EE

Total Views: 810

My name is Jean-Mathieu

I created this website so other people could enjoy finding useful stuff easier. If you have any question do not hesitate to contact me.

jean8mathieuCreated on 09/17/15


affiliate_link

Disclosure: We are a website that needs compensation to operate like any other website on the internet.
We may receive consideration for our reviews but we are totally unbiased and do not accept paid reviews or fake reviews claiming to be something they are not.