Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - MySQL - Create connection error

Tags:

java

mysql

I don't know why but this line gives me an error. I'm first making a few private strings, host, port, database, user and password. Then I'm setting those strings in the constructor.

Connection conn = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "?user=" + user + "&password=" + password);

This is the error message that I get:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Cannot load connection class because of underlying exception: 'java.lang.Number FormatException: For input string: "null"'.

What did I do wrong here?

like image 613
thijmen321 Avatar asked Nov 27 '25 09:11

thijmen321


2 Answers

The most likely cause is that one of your parameters is null. Probably port, since an attempt is made to convert it to a number.

Unless you are using a non default port (the default being 3306), you can just omit the port :

Connection conn = DriverManager.getConnection("jdbc:mysql://" + host + "/" + database + "?user=" + user + "&password=" + password);
like image 112
Eran Avatar answered Nov 29 '25 21:11

Eran


My guess, without seeing more code, is that port is null.

When you pass the string to the getConnection() method, it tries to parse out the port as a number. The when you concatenate a null value to a String, it appends 'null'. Now your string looks like jdbc:mysql://examplehost:null. Thus the java.lang.Number FormatException: For input string: "null".

like image 24
Azar Avatar answered Nov 29 '25 23:11

Azar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!