How do I properly add a mySQL connector in JAVA for JDBC?

error: package com.mysql.cj.jdbc does not exist
import com.mysql.cj.jdbc.MysqlDataSource;

java version: jdk 16
mysql version: 8.0
mysql driver version: 8.0.26

I already put the java connector along with the program files but I still have this error.
Here’s my code:

import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class conn {

    private static String servername = "localhost";
    private static String username = "root";
    private static String dbname  = "station_db";
    private static Integer portnumber  = 3306;
    private static String password = "";
    
    public static Connection getConnection()
    {
        Connection con = null;
        
        MysqlDataSource datasource = new MysqlDataSource();
        
        datasource.setServerName(servername);
        datasource.setUser(username);
        datasource.setPassword(password);
        datasource.setDatabaseName(dbname);
        datasource.setPortNumber(portnumber);
        
        try {
            con = datasource.getConnection();
        } catch (SQLException ex) {
            Logger.getLogger(" Get Connection -> " + con.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return con;
    }
    
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to list the version of JAVA, mySql, and the mySql driver.

This could be a classpath issue or incompatible versions between the 3 elements listed above or a typo in variable names. Any one of these three should throw this error.

Here is a basic tutorial for JDBC so you can review if you set things up properly.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x