0

I am trying to connect to a MySQL database using the code below, but my attempt fails.

This is my attempt:

private static Connection conn = null;
private static String url = "jdbc:mysql://localhost/";
private static String dbName = "proj1";
private static String driver = "com.mysql.jdbc.Driver";
private static String userName = "root";
private static String password = "root";

public static  int setupConnection ()
{
    try{
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url+dbName,"root","root");
        return 1;
    }
    catch (Exception e)
    {
        JOptionPane.showMessageDialog(null, e.getMessage());
        return 0;
    }
}

When installing MySQL, I remember entering the password "root", but I'm not 100% sure if the username is automatically assigned "root".

I get the error message : com.mysql.jdbc.Driver

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Marwan Tushyeh
  • 1,505
  • 4
  • 24
  • 47

4 Answers4

2

You need to add the MySQL Connector/J driver to the build-path/classpath of your Netbeans project. Otherwise it cannot be loaded.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
1

Unfortunately you did not mention what kind of failure you got. But here are some tips.

My JDBC URL looks like the following. jdbc:mysql://localhost:3306/MYSCHEMA. So port and schema name are missing in yours.

To check your credentials try to connect to your DB using command line client:

mysql -uroot -proot

Read the error message if you fail. If you cannot restore credentials, re-install MySql. It takes 3 minutes. Do not try to connect to DB using your code unless you can do it using existing clients.

Good luck.

AlexR
  • 114,158
  • 16
  • 130
  • 208
1

you should connect to port address 3306, change the url as below :

private static  String url = "jdbc:mysql://localhost:3306/";

I am considering that you are not getting any compilation error and you have added mysql java api..

dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
0

Start by trying to log into mysql from a command shell. If you can't, JDBC won't be able to, either.

This might help if you can't remember:

http://www.cyberciti.biz/tips/recover-mysql-root-password.html

duffymo
  • 305,152
  • 44
  • 369
  • 561