简体   繁体   中英

Java Cannot Connect to MySQL Server

I am trying to write a program in Java that in order to work, needs to have access to a MySQL database. Below is the code for the program so far, with the IP address, username, and password removed for security reasons. The problem with this code is that whenever it is run, it always fails to connect to the server, even though I know that it is running and that the password that the login information is correct. My friend found a program online that checks to see if your database can be connected to, and whenever he runs it, it always outputs "Where is your MySQL JDBC Driver?" What is the MySQL JDBC driver? I am assuming that it is the cause of my problem, but I don't know that for sure. Can anyone explain this to me?

import java.sql.*;

public class main
{
    public static void main(String[] args)
    {
        // Store the information to connect to the MySQL server in handy variables.
        String url = "jdbc:mysql://(IP REMOVED FOR SAFETY):3307/";
        String dbName = "attendance";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "(USERNAME REMOVED FOR SAFETY)";
        String password = "(PASSWORD REMOVED FOR SAFETY)";


        // Now let's connect!
        try {
            Class.forName(driver).newInstance();
            Connection conn = DriverManager.getConnection(url+dbName,userName,password);
        } catch (Exception e) {
            System.out.println("Could not connect to database!");
        }
    }
}

The problem could be that MySQL driver is not in your classpath.

Please look at this: http://dev.mysql.com/doc/connector-j/en/connector-j-installing-classpath.html

The MySQL JDBC driver is called MySQL Connector/J. This jar needs to be added to the classpath for your program to run.

The driver can be downloaded from: http://dev.mysql.com/downloads/connector/j/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM