mySQL connection won't work - java

I just can't connect to mySQL using Eclipse and can't figure out why.
Here is my connection class :
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class ConnexionBDD {
static String url = "jdbc:mysql://localhost:8888/Peoples?autoReconnect=true&useSSL=false";
static String login = "root";
static String password = "";
static Connection connection = null;
static Statement statement = null;
static ResultSet result = null;
static String request = "";
public static void main (String[] args) {
System.out.println("will load driver");
loadingDrive();
System.out.println("will connect");
connection();
}
public static void loadingDrive() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch ( ClassNotFoundException e ) {
e.getMessage();
}
}
public static void connection() {
try
{
connection = (Connection) DriverManager.getConnection(url, login, password);
System.out.println("Connected");
statement = (Statement) connection.createStatement();
result = statement.executeQuery(request);
}
catch ( SQLException e )
{
System.out.println(e.getMessage());
} finally {
if ( result != null ) {
try {
result.close();
} catch ( SQLException ignore ) {
}
}
if ( statement != null ) {
try {
statement.close();
} catch ( SQLException ignore ) {
}
}
if ( connection != null ) {
try {
connection.close();
} catch ( SQLException ignore ) {
}
}
}
}
}
Here is the result in the console :
will load driver
will connect
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
I have the connector (mysql-connector-java-5.1.41-bin.jar) in the file WebContent/WEB-INF/lib.
I installed mySQL on my mac.
I installed MAMP, I can reach phpmyadmin and add a new database, but it's kind of weird though, phpmyadmin is already logged as default and clicking the "Exit" button does not disconnect me I don't know why..
The url of phpmyadmin is :
http://localhost:8888/phpmyadmin/index.php
Why can't I connect to mySQL ?
EDIT :
I changed my url with the right port (8889) after checking out the mySQL port on MAMP, but nothing changed in the output of the console.

MySQL and phpMyAdmin cannot be on the same port.
Are you sure that your MySQL is not running on the default port? 3306
UPDATE:
If you are not already using Maven, please do so. It will aid you in managing your packages. That way you can avoid your method: loadingDrive()
I just ran you code locally with a test database. It runs fine for me.
I did the following changes to your code:
I removed the loadingDrive()
Altered request to static String request = "SELECT 1";. This query string is good for testing if the connection to the database is working properly.
I printed the request to the console:
result = statement.executeQuery(request);
System.out.println(result.next());
I added the mysql jdbc connector to my pom.xml file:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
After this I ran the code and this is the console output:
will connect
Connected
true
I still think your MySQL port is wrong. Do you run MySQL locally? Can you connect to it with phpMyAdmin?
I tried to change the url to contain the wrong port. I then received:
Could not create connection to database server. Attempted reconnect 3 times. Giving up.
So I strongly believe that your port is wrong. Can you try to change your url to the following?
static String url = "jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false";

Related

java.sql.SQLException: No database selected - but it is in the URL

I've been researching this for hours and understand that the database schema name should be in the URL. I have it in the URL, but I am still getting this error.
I am using Eclipse and Tomcat v9.0 and sql-connector version 8.0.28.
I have ensured to add the SQL connector everywhere, such as the Build Path, in the Tomcat Folder, in the Tomcat Server configuration, and I am still unable to access it.
In my web.xml I have the following:
<context-param>
<param-name>dbURL</param-name>
<param-value>jdbc:mysql://localhost:3309/logs</param-value>
</context-param>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
In my DBConnection class, I am able to successfully connect to the database with the following code:
package com.algonquin.loggy.dao;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverManager;
public class DBConnection {
// Database Schema
// CREATE DATABASE loggy DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
// CREATE TABLE logs (uuid CHAR(40) NOT NULL PRIMARY KEY, title CHAR(128),
// content TEXT, createTimestamp Date);
private static final String dbUser = "root";
private static final String dbPassword = "mypassword";
private static final String conString = "jdbc:mysql://localhost:3309//logs";
public static Connection getConnectionToDatabase() throws ClassNotFoundException {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// get hold of the DriverManager
connection = DriverManager.getConnection(conString, dbUser, dbPassword);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
System.out.println("Connection made to DB!");
}
return connection;
}
public static void main(String[] args) throws ClassNotFoundException {
getConnectionToDatabase();
}
}
Would greatly appreciate any support that can be given!

Create connection to SQL database using JDBC Driver- SQLException [duplicate]

I am trying to connect to my database by JDBC on localhost. Connecting via windows authentication is no problem, but I want to connect via SQL authentication. Therefore, I created a login and a user corresponding to this login in my database. I can normally log in SSMS:
My connection string for JDBC:
jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123
Thrown exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'doszke'. ClientConnectionId:b7005fe3-904d-40c5-a89e-af0cb61250d6
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:254)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:258)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:104)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4772)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3581)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3541)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2395)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2042)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1889)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1120)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:700)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:251)
at main.Main.main(Main.java:38)
The username and password are the same, as those used for loging to SSMS.
Here my class code:
package main;
import java.sql.*;
public class Main {
private static ResultSet selectStan(Connection connection) throws SQLException {
String sql_stmt = "SELECT * FROM STAN;";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql_stmt);
System.out.println("Select executed");
return result;
}
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String userName = "doszke";
String password = "doszke123";
String url = "jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123";
try (Connection con = DriverManager.getConnection(url)) {
if(con != null){
System.out.println("connected");
} else {
System.out.println("unable to connect");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
As Mark Rotteveel pointed out, I was trying to connect to a LocalDB instance with JDBC, which seemed undoable. (ref: here)
However, I installed jTDS and added to my classpath, changed my connection string to
jdbc:jtds:sqlserver://./TestBazyDanych;instance=LOCALDB#EB7165FD;namedPipe=true
create a connection by the use of this connection string, username and password and it worked. The instance pipe number was taken from cmd line via
sqllocaldb i MSSQLLocalDB
There are few things need to check:
Did you create doszke user under the database and SSMS?
Are you able to login with doszke/doszke123 credentials in SSMS?
Please check 1433 port are open or not in your inbound and outbound firewall.
Trying to telnet on localhost 1433. If it's getting failed change below setting:
Go to Configuration tools -> SQL Server Configuration Manager Select SQL Server Network Configuration -> Select protocol in the right side window enable tcp/ip and restart the services in services.

SQL Server conecction with jdbc eclipse

I have the following code to connect to my database in SQL Server:
public static void main (String [] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://DESKTOP-G8057U8\\SQLEXPRESS:1433;databaseName=Vaporizadores;integratedSecurity=true;";
DBConection=DriverManager.getConnection(url);
DBStatement = DBConection.createStatement();
System.out.println("Conexion exitosa");
}catch(ClassNotFoundException | SQLException e) {
System.out.println("Conexion fallida");
}
}
when I run it I get "Conexion fallida", meaning that an exception was catched. I've tried different urls but I still can't connect to my DB. I know very little about jdbc and sql server, so it may be a stupid error.
It worked like this:
String url = "jdbc:sqlserver://DESKTOP-G8057U8;databaseName=Vaporizadores;integratedSecurity=true;";
and i added the sqljdbc_auth.dll to Java bin folder

Connecting MySQL Database to NetBeans Error

I have a problem when running my code in NetBeans in order to see if mySQL is connected. This is the code:
public static void main(String[] args) {
Connection connect = null;
try{
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}
}
}
when I run it prints out "RIP". When I debugged it line by line, it went from the "connect = DriverManager.getConnection..." to "System.out.println("RIP"), and when I look at the "Exception e" it says "e = (java.sql.SQLNonTransientConnectionException) java.sql.SQLNonTransientConnectionException: Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: Malformed database URL, failed to parse the connection string near '=TRUE'."
Now, why is that?????
I think you need to add
Class.forName("com.mysql.jdbc.Driver"); .
Also, make sure everything in Connection conn = DriverManager.getConnection (String url, String user, String password); are set correctly.
From the url format in your code, it's like you are trying to get direct connect to specific table tUsers in your database. And I dont think that would work. Correct me if I'm wrong whether it's literally your database name or not.
Because the basic url format i know, should be like jdbc:mysql://localhost:3306/yourDBname .
If you already set the url correctly as is written in your post, then the code is
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/tUsers?autoReconnect=true/useSSL=TRUE","root","password");
if(connect!=null)
{
System.out.println("Connected");
}
}catch (Exception e)
{
System.out.println("RIP");
}}}
Hope that could do the work.

Java Wont connect to database no matter what driver

import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:3306:procomport";
//Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
//Connection connection = DriverManager.getConnection(url , userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
This is my code I have multiple different databases but it wont connect to any of them what's the problem with this? I keep getting the error it cannot connect to the database. Although I can connect to it using other management tools is it a driver issue? How would I be able to tell if I had the drivers necessary?
The code you've provided to connect to the database won't connect to either MySQL nor Oracle as it stands because it's a mish-mash of attempts to connect to both.
For Oracle, the code should look something like:
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:1521:procomport";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
(assuming you have a user called root on Oracle, and the Oracle SID is procomport). Note in particular the change of port number: MySQL typically uses 3306, Oracle uses 1521.
For MySQL the connection code should look like:
String userName = "root";
String password = "password123!";
String url = "jdbc:mysql://localhost:3306/procomport";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
(assuming your MySQL database is called procomport). Note the different style of connection URL and the driver class name.
The Oracle driver is typically in a JAR file named ojdbc6.jar, and the MySQL in a JAR named something like mysql-connector-java-5.1.18-bin.jar.
Finally, when you write something like
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
you really aren't helping yourself. The exception e will almost certainly contain the reason why your database connection code isn't working, but by deliberately ignoring it you're making it much harder for yourself to figure out what has gone wrong.
To be honest with you, I'd be tempted to declare the main method throws Exception (by adding this to the end of the public static void main... line), and then you can delete your unhelpful catch block. If an exception is thrown and not handled within main, the JVM will print the stack trace for you before it exits.
After your:
System.err.println();
Place a:
e.printStacktrace();
Then you will see real error message. Probably the driver classes are not in the classpath.
Hope this will help you
Uncomment the line Class.forName("oracle.jdbc.driver.OracleDriver");
Make sure you have the Oracle dirver "oracle.jdbc.driver.OracleDriver" in the classpath

Categories