How to connect to IntelliJ Ultimate's LocalHost MySQL database? - java

I went to Database > + > Data Source > MySQL
Here's what my panel looks like:
This is the error:
[08S01]
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
java.net.ConnectException: Connection refused: connect.
and here's my connection file:
package sample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection
{
private static Connection connection;
private static final String user = "root";
private static final String password = "root";
private static final String database = "jdbc:mysql://localhost:3306/user";
public static Connection getConnection()
{
if (connection == null)
{
try
{
connection = DriverManager.getConnection(database, user, password);
} catch (SQLException e)
{
e.printStackTrace();
System.out.println("Could not open database.");
System.exit(1);
}
}
return connection;
}
}
What could be my problem? I tried searching up for what others have tried but none of them seemed to work and I had to make several copies of my entire project because I kept messing things up trying those solutions to no avail. More specifically Solving a "communications link failure" with JDBC and MySQL

You need to have MySQL server installed and running to be able to connect to it from the other apps.

I suppose that your program did not run and so you went to configure some datasource in Intelij to make a connection with your Database.
If that is the case then
Your db is not reachable. Check if it is running and if all information provided here is correctly.
You don't need to set a InteliJ Datasource for your program to run. That is only for you to execute sql scripts using Intelij. It has nothing to do with some program that you develop using java which connects to that database.

Related

Using Java to Connect to MySQL Connection from multiple computers

A few classmates and I are creating a Java project which requires a database. I have created a connection in MySQL and connected it to my Java project successfully using the following Connect class:
package com.example.javaworkoutgame.Model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connect {
static Connection con;
public Connect() {
connect();
}
// attempt to connect to MySQL database
public static void connect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("Driver Loaded Successfully");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/lab3", "root",
"**********"); // not the actual password
System.out.println("Successful Connection");
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
} catch (SQLException sqle) {
System.err.println(sqle);
}
}
}
This code runs properly on my machine.
I committed and pushed the code to Bitbucket so my partners could access it. However, when they run the code on their computers, they get the following error message:
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
Is there something I need to change in MySQL workbench in order for other people to be able to access the database? I could not find any information on this.
The only thing I was able to try was found at this thread:
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
I opened a new .sql file and tried running the command:
GRANT ALL PRIVILEGES ON . TO 'root'#'localhost' IDENTIFIED BY '%password%' WITH GRANT OPTION;
(I replaced '%password%' with the actual password)
When I tried that I got the following error message:
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IDENTIFIED BY '*********' WITH GRANT OPTION'
No, and you need to stop this line of thought and do some research first.
Your current configuration says that the mysql server is on the very same physical machine that the code is running on. You installed mysql on your dev machine, your friends need to install it on theirs, and each has their own unique database (nothing is shared).
You could, instead, take your mysql server, open it up to the world (which, for virtually all ways internet is made available in residential connections, requires messing with your router to 'open a port').
But then you have an open mysql server, and the username and password are on a public bitbucket site.
It also requires either a permanent IP (which few residential internet providers offer) or a dyndns service. More generally, hosting open MySQL servers that see lots of traffic gets your internet shut down, for good reason. You'd end up hosting a whole bunch of hackers. All hardware in your network will be p0wned and turned into bot nets. Hence, very very bad idea.
Good ways to solve this problem:
Everybody installs their own MySQL server. This is sensible; you're writing code and bound to make mistakes, it'd be real bad if all code you write is first-run and tested on live data. You don't want one of your friends to wipe your database. If you need some initial data to test with, set it up properly, and read up on how to make an SQL dump. With such a dump file you can reset any mysql server to that exact state - and that'd be how you and your friends develop: Set up the DB to be in that known state, write some code, and if you ruin the db by doing so, no problem. Just reset it again.
Set up a VPN between your friends. NOW you can share the IP your system has within the VPN (it'll be 10., 172.16., 192.168.* - if it's 127.0.0.1, it's localhost, i.e. everybody needs to install mysql on their own and nothing is shared, and if it's anything else, you're opening it to the world, which you don't want to do). Do not put the VPN username/password info anywhere in that bitbucket. And you need to trust your friends.
You should have a properties type file so that each person who is going to interact with the code has their local data without the need to replicate yours, in the same way you can have different values ​​in the properties for test or production environments.
example of a property file:
system.properties
#BD
db.driver=com.mysql.cj.jdbc.Driver
db.user=user
db.pass=password
db.server=server_IP
db.port= port_IP
db.db = DB
Then you should have a procedure to read from java the properties inside the file
Utils.java
package com.example.javaworkoutgame.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public final class Utils {
public static Properties getProperties() {
String path = String.format("PATH to your properties FILE/system.properties",
System.getProperty("user.dir"));
Properties properties = new Properties();
try (InputStream is = new FileInputStream(new File(path))) {
properties.load(is);
} catch (IOException e) {
throw new IllegalStateException(e);
}
return properties;
}
}
And finally you make a call to the function that gets the properties from your connection class
Connect.java
package com.example.javaworkoutgame.Model;
import com.example.javaworkoutgame.util.Utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Connect {
Properties properties = Utils.getProperties();
static Connection con;
public Connect() {
connect();
}
// attempt to connect to MySQL database
public static void connect() {
try {
String driver = properties.getProperty("db.driver");
String ip = properties.getProperty("db.ip");
String port = properties.getProperty("db.port");
String db = properties.getProperty("db.db");
String user = properties.getProperty("db.user");
String pass = properties.getProperty("db.pass"):
Class.forName(driver);
System.out.println("Driver Loaded Successfully");
con = DriverManager.getConnection("jdbc:mysql://"+ip+":"+port+"/"+db, user,
pass);
System.out.println("Successful Connection");
} catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
} catch (SQLException sqle) {
System.err.println(sqle);
}
}
}
About the MYSQL error, if your partners do not have a local mysql environment with the same values ​​as you, they will experience the error you describe, since your configuration is a local configuration, if you need your partners to connect to your pc, you must open the ports of mysql and give them your public IP (not recommended)
I hope this answer helps you!

MS SQL Connection: Android Studio never connects vs Eclipse IDE does

I am creating a program for a local organization to take inventory. App connects to SQL Server via MSSQL 8.2 connector. App on phone should allow for receiving and sending item information. I have a static class to connect to the database, that handles the connection. In Eclipse, I am able to successfully connect and query the database. In Android studio, I get errors on every attempt to connect.
-Server is hosted on same pc.
-Ports have been configured, repeatedly. Currently have inbound and outbound rules for TCP and UDP fully open. Dynamic ports are on for SQL server. Services for SQL server have been restarted dozens of times. 1433 has been enabled and toggled off, but are currently blank.
-Attempted to connect by IP address, host cannot be resolved
-Permissions edited to allow login access to modify the database
-Integrated security and TLS security tried at different times, both failed.
List of errors:
Connection to the host BLACK-G, "xxxxx" port 1433, has failed.
TCP/IP connection to the host failed, unable to resolve host.
Connection to the host named BLACK-G instance sqlexpress failed,No
address associated with hostname, open up UDP traffic to port 1434
Unknown host exception. Unable to resolve host BLACK-G
Connection Refused
Failed to connect
Connection to the host 192.168.1.219 has failed. Failed to connect to
192.168.1.219 (port 1433) from 192.168.1.87(port 33654) after 2478ms Verify connection properties.
Here is the code
package com.example.ccupboard_1;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseJAVA {
// #RequiresApi(api = Build.VERSION_CODES.KITKAT)//public static void main(String[] args) {
public static String Connect() {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://BLACK-G\\SQLEXPRESS;user=ay7;password=343434;databaseName=ayTestDatabase2;" ;
ResultSet resultSet = null;
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();) {
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT Fname, Lname from dbo.Customers";
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
result += (resultSet.getString("Fname") + " " + resultSet.getString("Lname")+"\n");
}
} catch (SQLException e) {
e.printStackTrace();
result = e + "";
}
return result;
}
}
Snippet from main activity that calls connect method:
case R.id.buttonSignOut: { //used to test connection currently, simply attempts to connect and //returns the value to a textview on the page
Thread thread = new Thread() {
public void run() {
textviewLowItemAlert.setText(DatabaseJAVA.Connect());
}
};
thread.start();
break;
What would be the next step in resolving this issue? It works in Eclipse, but not in studio. I've tried more than a dozen different connection Strings, and most of them threw the same errors. Does my server not allow access to Android Studio? Most of the errors seem to be Android studio being incapable of locating it on the server.
Here's a snippet from a working app of mine where I can connect succesfully to a local ms sql.
In a config file I set the connection info.
public static String dbUser = "user";
public static String dbPassword = "password";
public final static String sqlString = "jdbc:jtds:sqlserver://ip:port//INSTANCENAME";
Then I start the connection like this.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
DriverManager.setLoginTimeout(5);
connection = DriverManager.getConnection(Config.sqlString, Config.dbUser, Config.dbPassword); // Connect to database
if (connection == null) {
ConnectionResult = "Verify Internet Connection";
Toast.makeText(activity, ConnectionResult, Toast.LENGTH_LONG).show();
Finally just do the query and close the connection.
Alright, was finally able to figure it out, with the JDBC-JTDS connector mentioned by JoaquinAlvarez.
Here's what happened:
-Used the connection info he provided, with my IP address, and a higher timeout
-Network Error IOException, EHOSTUNREACH(No route to host),
-Router changed my IP address, so had to fix that
-After that, I used my PCNAME\SQLEXPRESS for the the for the instance
-It returned Instance Unreachable, so I changed to SQLEXPRESS alone
-Then it returned DB Closed connection
-I looked at Windows Event Viewer, and it said:
"Encryption is required to connect to this server but the client library does not support encryption; the connection has been closed. Please upgrade your client library."
-I checked the SQL server in SQL SERVER Configuration Manager... Force Encryption was turned on.
-Tried again, and the JTDS connector finally connected to the Database and I was able to do things. No help with the MSSQL one yet though.
Thank you Mr. Alvarez!

Trouble connecting to local database with JDBC - no error after executing the code

This code isn't providing the connection to my local database. There is no error after executing the code below. Connecting with JDBC using DriverManager:
package first;
import java.sql.Connection;
import java.sql.DriverManager;
public class Demo {
public static void main(String[] args){
Connection con=null;
try{
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","XXXXXXXX");
if(con!=null)
{
System.out.println("connected successfully");
}
}
catch(Exception e)
{
System.out.println("not connected to database");``
}
}
}
When troubleshooting a connection string one of the first steps is to try to connect using another tool that allows a nice user interface for providing the connection information. In this case you could MySql Workbench which comes with the community edition of MySql. Once you have a solid connection using the tool you can then copy the connection string it uses to your code. This will help eliminate the connection string errors in your code.
In addition as #Elliot Frisch suggested outputting the stacktrace should give you some good information to help troubleshoot your connection string, as well.

Can't connect to MariaDB Database [JAVA]

I'm working on a Twitch Chat Bot which should output messages when someone types a command. The commands are getting saved in a MariaDB Database called TB. The first problem I have is that I cant connect to the Database. I saw a lot of stackoverflow posts but none of them could help me. I've never connected a database to a java program before.
My database connect method:
public void DBConnect(){
try {
String url = "jdbc:mariadb://localhost:3306/TB";
String user = "root";
String password = "";
Connection con = DriverManager.getConnection(url, user, password);
if (con != null) {
System.out.println("Connected to the database test");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
I'm executing the method whenever I run my program:
public TwitchBotFenster() throws IOException, Exception {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
initComponents();
ReadServerMessages.start();
DBConnect();
}
The exception I get looks like this:
java.sql.SQLException: No suitable driver found for jdbc:mariadb://localhost:3306/TB
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at main.TwitchBotFenster.DBConnect(TwitchBotFenster.java:166)
at main.TwitchBotFenster.<init>(TwitchBotFenster.java:31)
at main.Main.main(Main.java:9)
I have already downloaded the jdbc and imported it to my library. Apache and MySql are running on XAMPP.
If you're using Maven it may be fastest to shade the jdbc into your JAR. Essentially what's happening right now is that you're able to code with it because you have the dependency listed, but when you actually run your bot you're not loading the dependency.

Java : Failing to connect to mySql DB

I just set up a local mySql database. I can connect to it properly through command line and third party software (Navicat..).
Server: localhost:3306
User: root
Password: password
Database name: students
However, when I try to connect with java, I get an error.
CODE:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Sql {
public static void main(String[] args) {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306//students?autoReconnect=true&useSSL=false",
"root", "password");
Statement sqlState = conn.createStatement();
} catch (SQLException ex) {
System.out.println("SQLException" + ex.getMessage());
System.out.println("SQLException" + ex.getSQLState());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
OUTPUT:
SQLExceptionCould not create connection to database server. Attempted reconnect 3 times. Giving up.
SQLException08001
Also tried:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306//students", "root", "password");
and
conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306//students?autoReconnect=true&useSSL=false","root", "password");
Additional Attempts:
The firewall is disabled.
I installed the Jconnector by putting the .bin.jar in:
C:\Program Files\Java\jdk1.8.0_73\jre\lib\ext
I can see it on the left under JRE in Eclipse and the import doesn't give errors.
NOTEs:
Using mySQL from the terminal, workbench or Navicat gives no errors, any query works, the local server is running properly and the credentials are correct, the user has full admin priviledges.
Any suggestions?
I recently had a similar issue. My issue ended up being that the MySQL server version was 8.0.19, while flyway was using a 5.1.40 version of the java MySQL library.
Once I updated the MySQL library version to 8.0.19, my errors went away.
This exception can have 4 causes:
User does not have privileges to connect to database.
MySQL service is not running.
Incorrect MySQL-Connector Jar.
Database URL is incorrect;.
Check above prerequisites before connecting to MySQL database.

Categories