0

I have ubuntu 20.04.6. Openjdk 11. mysql-connector-java-8.0.20.jar, renamed to mysql.jar CLASSPATH="/var/www/html/java/mysql.jar", classpath stablished in ~/.bashrc After installing openjdk 11 and set classpath, still can't execute my app from linux terminal. I give you the source code:

import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class mysql {
    public static void main(String args[]) {
        Connection conexion=null;
        Statement instruccion=null;
        ResultSet conjuntoresultados=null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conexion=DriverManager.getConnection("jdbc:mysql://localhost:3306/galpon","root","password");
            instruccion=conexion.createStatement();
            conjuntoresultados=instruccion.executeQuery("select usuario,cbu from duenos");
            ResultSetMetaData metadatos=conjuntoresultados.getMetaData();
            int numerocolumnas=metadatos.getColumnCount();
            System.out.printf("Dueños de vehículos:");
            for(int i=0;i<numerocolumnas;i++)
                System.out.printf("%-8s\t",metadatos.getColumnName(i));
            System.out.println();
            while(conjuntoresultados.next()){
                for(int i=0;i<numerocolumnas;i++)
                    System.out.printf("%-8s\t",conjuntoresultados.getObject(i));
                System.out.println();
            }
        }
        catch (SQLException sqlexcepcion) {
            sqlexcepcion.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                conjuntoresultados.close();
                instruccion.close();
                conexion.close();
            }
            catch ( Exception excepcion )
            {
                excepcion.printStackTrace();
            }
        }
    }
}

The error message is:

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver 
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581) 
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) 
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:527) at java.base/java.lang.Class.forName0(Native Method) 
    at java.base/java.lang.Class.forName(Class.java:315) 
    at mysql.main(mysql.java:13) 

java.lang.NullPointerException at mysql.main(mysql.java:39)

Thanks for every help you can give me

I tried installing mysql connector by its deb installer downloaded from mysql downloads. Did not work. Then download mysql connector java 8.0.20.jar ,renamed to mysql.jar alocated in /var/www/html/java, then set CLASSPATH=/var/www/html/java/mysql.jar in ~/.bashrc, then reloaded bashrc by "source ~/.bashrc". Nothing of this works for me. I don't know why

5
  • 2
    CLASSPATH="/var/www/html/java/mysql.jar" is not the effective classpath. If it were you wouldn't be able to run your app as it's not in the classpath (assuming what is in the classpath you mention is the renamed driver jar [not sure why you decided to do that]) ALso set CLASSPATH=/var/www/html/java/mysql.jar is wrong. It should be export CLASSPATH=/var/www/html/java/mysql.jar but see my previous comment about the classpath and your app class. You'd be better off doing java -cp .:/var/www/html/java/mysql.jar mysql (Java class names begin upper case though) Commented Sep 4, 2024 at 21:42
  • Don't rename the jar, it is a bad practice. It loses the original name and version, si it is difficult to say what it is used. The road to jar hell is paved of jar renames. Commented Sep 5, 2024 at 3:34
  • I renamed it for remember it easier. Above this post is the original name and version. "mysql-connector-java-8.0.20.jar". I do it "export CLASSPATH=/var/www/html/java/mysql.jar " just right now, and the new error message is (I translated it because the error is in Spanish): "Error: mysql main class not found or loaded. Caused by: java.lang.ClassNotFoundException: mysql". If i do "echo $CLASSPATH" it prints the full path of the jar file. I keep reading your comments Commented Sep 5, 2024 at 5:14
  • export CLASSPATH=/var/www/html/java/mysql.jar " just right now, and the new error message is... Yes, as I said it would be. I gave you the correct command. Don't set classpaths as environment variables. It's unnecessary and will lead to problems in the end Commented Sep 5, 2024 at 5:27
  • 1
    "I renamed it for remember it easier." - Except ... now you have no easy way of knowing what it was before you renamed it. So ... in 3 months time (or probably sooner) you won't know what version of the driver you are using. Commented Sep 5, 2024 at 5:34

1 Answer 1

1

Classpath

Determine the classpath in effect at runtime by querying a System property.

String classpath = System.getProperty( "java.class.path" );

Excerpt of classpath that contains MySQL JDBC driver, while running within my IDE (IntelliJ).

…/com/mysql/mysql-connector-j/9.0.0/mysql-connector-j-9.0.0.jar:…

Dependencies

Manually downloading, installing, and configuring libraries needed by your project, such as JDBC drivers, is an annoying and troublesome chore. Automate it.

Java work is so much easier with a build management tool like Apache Maven or Gradle. Either of these tools is well worth the time taken to learn their basics.

Either of those tools will locate a copy of any needed libraries that you specify, download them from a repository on the internet, and install them appropriately into your project.

If using Maven, create a new project using a Maven archetype like Quickstart. The new project includes a POM file for you to edit.

Specify the JDBC driver as a dependency.

  <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
  <dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>9.0.0</version>
    <scope>compile</scope>
  </dependency>

Notice the scope element with value compile. That tells Maven to obtain a copy of the JDBC driver, use that copy for compiling, and include a copy into the final software artifact (likely a JAR file). See manual.

In a Web app, rather than a desktop app (console or GUI), you may want instead a scope of provided if you expect the JDBC driver to be already installed on your Jakarta Servlet container/server.

Code

Looks like your JDBC code came from an outdated tutorial. Here are some improvements.

Class.forName("com.mysql.cj.jdbc.Driver");

Calling Class.forName has been unnecessary for many years now. JDBC was rearchitected long ago to automatically load and register all available JDBC drivers via Java Service provider interface (SPI).

Make a habit of using DataSource interface & implementation. In real work, this enables you to eventually externalize your database connection info (username, password, server address, etc.) outside of your source code. In the meantime, write a method like this:

private DataSource dataSource ( )
{
    com.mysql.cj.jdbc.MysqlDataSource dataSource = new com.mysql.cj.jdbc.MysqlDataSource();  // Implementation of `DataSource`.
    dataSource.setServerName( "localhost" );
    dataSource.setPortNumber( 3306 );
    dataSource.setDatabaseName( "example_db_" );
    dataSource.setUser( "scott" );
    dataSource.setPassword( "tiger" );
    return dataSource;
}

Use try-with-resources syntax to simplify your code while automatically closing your opened database resources.

String sql = … ;
try
(
    Connection connection = dataSource.getConnection() ;
    Statement statement = … ;
    ResultSet resultSet = … ;
)
{
    … Handle your ResultSet. 
}
catch ( … )
{
    … Handle error conditions.
}
// Your Connection, Statement, and ResultSet objects will all be closed at this point, even if Exception is thrown.

You will find the source code for multiple full example apps demonstrating JDBC with MySQL, H2, and Postgres written by me, not to mention other great existing material on Stack Overflow. Search to learn more.

Example POM

Here is an example of a Maven POM created by Quickstart archetype, then adjusted by me to update all versions, and to use Aggregator edition of JUnit Jupiter.

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>work.basil.example</groupId>
    <artifactId>ExMySql</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>ExMySql</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.release>22/maven.compiler.release>7</maven.compiler.release>
    </properties>

    <dependencies>

        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>5.11.0</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>9.0.0</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>

    <build>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.4.0</version>
                </plugin>
                <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.3.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.13.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>3.3.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-jar-plugin</artifactId>
                    <version>3.4.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>3.1.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>3.1.2</version>
                </plugin>
                <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
                <plugin>
                    <artifactId>maven-site-plugin</artifactId>
                    <version>3.12.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-project-info-reports-plugin</artifactId>
                    <version>3.6.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
Sign up to request clarification or add additional context in comments.

1 Comment

Ok Thanks Basil Bourque for your answer. I am going to do what you recommend, and then I'll tell you how it turned out. Thanks g00se, thanks aled

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.