Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+10 votes
3 views
in Python by (750 points)
edited by

I want my database to communicate with my java programs

Can anyone provide me with a sample program using JDBC?

I’m getting an error while doing the same

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 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.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2260)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:787)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:49)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:357)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
    at java.sql.DriverManager.getConnection(DriverManager.java:582)
    at java.sql.DriverManager.getConnection(DriverManager.java:207)
    at SqlTest.main(SqlTest.java:22)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: 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.
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1122)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:344)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2181)
    ... 12 more
Caused by: java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at java.net.Socket.<init>(Socket.java:375)
    at java.net.Socket.<init>(Socket.java:218)
    at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
    at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
    ... 13 more

Contents of my text file are given as follows:

    import com.mysql.jdbc.*;

    import java.sql.connectionA;

    import java.sql.DriverManagerB;

    import java.sql.PreparedStatementC;

    import java.sql.ResultSetD;

    import java.sql.SQLExceptionE;

    import java.sql.StatementF;

    public class Test {

       public static void main(Stringxyz [] args) throws Exception {

           // Class.forName( "com.mysql.jdbc.DriverWXY" ); // do this in init

           // // edit the jdbc url

           connectionA conn = DriverManager.getConnection(

               "jdbc:mysql://localhost:3306/projects?user=usera&password=12345");

           // StatementF F = conn.createStatement();

           // ResultSetD D = st.executeQuery( "select * from table" );


           System.out.println("Connected or not?");


       }

Contents of the test file:

import com.mysql.jdbc.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SqlTest {

    public static void main(String [] args) throws Exception {
        // Class.forName( "com.mysql.jdbc.Driver" ); // do this in init
        // // edit the jdbc url
        Connection conn = DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/projects?user=user1&password=123");
        // Statement st = conn.createStatement();
        // ResultSet rs = st.executeQuery( "select * from table" );

        System.out.println("Connected?");
    }
}
 

4 Answers

+13 votes
by (10.5k points)
  • Your exception seems to indicate that your MySQL server is not available.

         Exception in thread “main” com.mysql.exceptions.jdbc4.

         CommunicationsException:

         Communication link failure.                                                                                             The last packet sent successfully to the server was 0 milliseconds ago.                               No packet has been received by the driver from the server.   

  • Now, trying from the terminal:

Mysql -u username -p

  • You will be asked for the password associated with the username. Does the MySQL client connect after providing the correct password?
  • You might have to start MySQL from the preferences. If not, you can also set it to run at the startup.
+3 votes
by (32.3k points)
edited by

The issue that you are facing can means that the DB isn't reachable at all. This problem can occur due to any reason may be IP address or hostname in JDBC URL is wrong, or the hostname in JDBC URL is not recognized by local DNS server, or Port number may be missing, or DB server is down. There can be many reasons, so I would suggest you go through your approach once again and keep a check on everything.

I also got this error once because I didn't start my server before running this program.

I ran my program without starting the MySQL server.

So, I did cross-checking and after starting the MySQL server, everything was fine.

You can also try another approach where you can do replacement of Localhost to your IP address:

Connection con = DriverManager.getConnection(

 "jdbc:mysql://localhost:3306/DBname", "root", "root");

 Connection con = DriverManager.getConnection(

 "jdbc:mysql://192.100.0.000:3306/DBname", "root", "root");

You can use the following video tutorials to clear all your doubts:-

I hope it solves your problem.

You can learn in-depth about SQL statements, queries and become proficient in SQL queries by enrolling in our industry-recognized SQL course.

0 votes
by (37.3k points)

The error message you are getting indicates that your Java application is not able to establish a connection with your MYSQL server.

Here is a script to achieve the same. 

Sample code: 

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class SqlTest {

    public static void main(String[] args) {

        Connection conn = null;

        Statement stmt = null;

        ResultSet rs = null;

        try {

            // Load your MySQL JDBC driver 

            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish a connection

            conn = DriverManager.getConnection(

                "jdbc:mysql://localhost:3306/projects?useSSL=false", "user1", "123");

            // Create a statement object to execute queries

            stmt = conn.createStatement();

            // Execute a query

            rs = stmt.executeQuery("SELECT * FROM your_table_name");

            // Process the result set

            while (rs.next()) {

                // Retrieve and print data from result set

                int id = rs.getInt("id"); // assuming the column name is 'id'

                String name = rs.getString("name"); // assuming the column name is 'name'

                System.out.println("ID: " + id + ", Name: " + name);

            }

            System.out.println("Connected successfully!");

        } catch (SQLException e) {

            e.printStackTrace();

        } catch (ClassNotFoundException e) {

            e.printStackTrace();

        } finally {

            // Clean up resources

            try {

                if (rs != null) rs.close();

                if (stmt != null) stmt.close();

                if (conn != null) conn.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

    }

}

0 votes
by (3.1k points)

This kind of error is mostly seen when server fails to load data but that’s not always the case there can be other reasons as well like 

Database Server is Down: 

The MySQL server is not running. The status can be checked via the following command lines : 

systemctl status mysql   # For systemd systems 

service mysql status     # For init.d systems 

Bad Connection URL: 

Verify your JDBC connection URL is spelled correctly. It should follow this pattern: 

jdbc:mysql://hostname:port/databaseName 

Hostname, port which defaults to 3306, and database name are both correct. 

Firewall Issue: 

Ensure that no ports of MySQL are blocked by a firewall. You may need to include your firewall rules or it may require additional openings to allow traffic in some ports. 

Network Problem 

You can use ping or telnet to test if network is working between your application and MySQL server. 

ping hostname 

telnet hostname 3306 

MySQL configuration 

Ensure that the MySQL server allows remote connections. Look at your my.cnf or my.ini configuration file for bind-address. If you want to access it remotely, it should not be set to 127.0.0.1. 

User Authentication Issues: 

Ensure that the user has the correct privileges and is connecting from the correct host. You can check user privileges with the following query: 

SELECT host, user FROM mysql.user; 

Timeouts: 

Increase the connection timeout settings on your JDBC URL, for example: 

jdbc:mysql://hostname:port/databaseName?connectTimeout=5000 

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...