Error connecting to my database via ODBC when running from a .jar

167 views Asked by At

I can't connect to my data base while I run my .jar,but I can do it if I run my project in NetBeans. I'm using the JDBC-ODBC Bridge for the connection. Here's the function I use for the connection.

public Statement connection(Statement st){
    try {
        // connection avec la base de donnée DataBase.
        // On charge le driver ODBC
        Properties props = new Properties();
        // pour pouvoir afficher les accents et les caractères spéciaux!!
        props.put ("charSet", "ISO-8859-15");
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        cnx = DriverManager.getConnection("jdbc:odbc:DataBase", props);
        st=cnx.createStatement();
        //JOptionPane.showMessageDialog(null,"connection ouverte avec     succès");
    }catch(Exception e)
    {
        System.out.println(e.getLocalizedMessage());
        return st;
    }
    return st;
}

Sample Image:

enter image description here

1

There are 1 answers

0
Gord Thompson On

When a Java application is distributed to other users as a .jar file, we may not have control over the Java Runtime Environment (JRE) under which it runs. If the application has specific requirements for the JRE version then it should check the version explicitly.

For example, an application that uses the JDBC-ODBC Bridge must run under Java 7 or earlier because that component was removed from Java 8. So, the application code should do something like this:

int javaVersion = Integer.valueOf(
        System.getProperty("java.runtime.version").split("\\.")[1]);
if (javaVersion > 7) {
    System.out.printf(
            "This application is running under Java %d. " + 
            "Java 7 or earlier is required.%n", 
            javaVersion);
    System.exit(1);
}

java.com now distributes Java 8 by default. Most users who go to that website and click the handy "Free Java Download" button will almost certainly end up with Java 8 (or newer). If the application does not check the Java version and blithely tries to use the JDBC-ODBC Bridge then it will crash.

With the above check in place the user will see the considerably more helpful message

C:\__tmp>java -jar JdbcOdbcTest.jar
This application is running under Java 8. Java 7 or earlier is required.

If they run it using a JRE for Java 7 or earlier it will just work:

C:\__tmp>"C:\Program Files\Java\jre6\bin\java" -jar JdbcOdbcTest.jar
Welcome to our app!