How To Use JDBC Driver - Java Community

How To Use JDBC Driver

create connection java and postgres

How to use JDBC Driver for Postgres, So that applications you have created can be connected to the database server. You must create a class connection to do that. You also need a postgres jdbc driver library. Postgres JDBC Driver download.

You can following java step by step tutorial :
  1. Create New Project -> Java -> Java Application - > Next. 
  2. java aplikasi

  3. Rename Project Name, unchecklist Create Main Class and click Finish.
  4. java aplikasi

  5. Right-click the project -> New -> Java Class.
  6. Rename Class Name and Package and then click Finish.
java aplikasi
Source Code :

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author Akira
 */
public class ConnectionManager {

    private Connection conn_m= null;

    public ConnectionManager(String dbserver){
        try {
            String driver = "org.postgresql.Driver";
            String url = "jdbc:postgresql://localhost:5432/"+ dbserver;
            String username = "postgres";
            String password = "postgres";
            
            Class.forName(driver);
            conn_m = DriverManager.getConnection(url, username, password);
            System.out.println("Connection Success !!!");
        } catch (ClassNotFoundException ex) {
            System.out.println("ERROR : Class Not Found");
        } catch (SQLException ex) {
            System.out.println("ERROR JDBC Configuration");
        }
    }

    public Connection getConnection() {
        return conn_m;
    }
    
    public static void main(String[] args){
        ConnectionManager obj = new ConnectionManager("db_student");
        obj.getConnection();
    }

}

Java class ConnecionManager above functions perform connection database "db_student" in PostgreSQL.
If the connection is successful, it will display a message Connection Success !!!
"ERROR : Class Not Found" message will appear if you do not add a library PostgreSQL JDBC Driver. Please add the library to fix this.

While the y error message will appear if you are wrong in configuring URL, username, password, no database or database name wrong. please check the configuration again. customize to your database.

Please leave a comment if you have any problems about the database connection.

Subscribe to receive free email updates:

0 Response to "How To Use JDBC Driver"

Posting Komentar