0

I am new to Java and developing a Swing application, so this project is all depending on JDBC, its very big project for me, i am trying to create a single Connection Class and use it in my entire project.

i have written a code to get connecton

package sab;

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

public class ConnectionManager {

private static String url = "jdbc:h2:~/test";    
private static String driverName = "org.h2.Driver";   
private static String username = "sa";   
private static String password = "";
private static Connection connection;
private static String urlstring;

public static Connection getConnection() {
    try {
        Class.forName(driverName);
        try {
            connection = DriverManager.getConnection(url, username, password);
        } catch (SQLException ex) {
            // log an exception. fro example:
            System.out.println("Failed to create the database connection."); 
        }
    } catch (ClassNotFoundException ex) {
        // log an exception. for example:
        System.out.println("Driver not found."); 
    }
    return connection;
}

public static void main(String[] args) {

    getConnection();
}

}

but when ever i am trying to test connection it show

Failed to create the database connection.
Driver not found.

i dont Know what am doing wrong someone please help

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Intact Abode
  • 382
  • 5
  • 20
  • 2
    Show us the stack-trace of your `SQLException` `ex.printStackTrace()` – Mihir May 10 '17 at 05:24
  • If you include `ex.printStackTrace()` in your catch blocks it should tell you exactly why the connection is failing. Examining the stack trace is very important when debugging. – Rocky May 10 '17 at 06:30

1 Answers1

0

Sorry friends i have created the connection good,thanks @Mihir and @Rocky that helped, its actually ClassNotFoundException, forgot to add Jar file to my project. my mistake!

Intact Abode
  • 382
  • 5
  • 20