I try to connect to SQL DB through java. When i run the code, in the console is printed: Connecting to database... then nothing happens and i have to stop the program.
package javasqltest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JavaSQLTest {
static final String JDB_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:1527/";
static final String USER = "test";
static final String PASS = "test";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException se2) {
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
Any help for fixing this issue.
Thanks in Advance.
LE:
If i change the port to 3306 this is the console output:
run:
Connecting to database...
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:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
Goodbye!
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1117)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:355)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2461)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2498)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2283)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:822)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at javasqltest.JavaSQLTest.main(JavaSQLTest.java:27)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:244)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:259)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:305)
... 15 more
BUILD SUCCESSFUL (total time: 2 seconds)
The MySQL JDBC connection URL usually looks something like this:
jdbc:mysql://localhost:3306/dbname
where dbname is the name of your MySQL database, and 3306 is the default port on which MySQL is listening. If your MySQL be really listening on port 1527 then you can use that instead. You never specified the name of a database, and this alone would cause the connection to fail.
Related
This question already has answers here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
(51 answers)
Closed 4 years ago.
I have settled MAMP on my machine and last time when I used that code on my old computer and with another database that works pretty well. Now I cannot understand where I am wrong.
public class JDBC {
private static String DBURL = "jdbc:mysql://localhost:3306/BookReservationDatabase";
private static String DBLOGIN = "root";
private static String DBPASSWORD = "root";
public static void main(String[] args) {
// Step1: register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// Step 2: Establish the connection to the database
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
conn = DriverManager.getConnection(DBURL, DBLOGIN, DBPASSWORD);
// Step 3: Create statements (SQL queries)
stmt = conn.createStatement();
// Step 4: Execute statements and retrieve results
rset = stmt.executeQuery("SELECT * FROM Users");
// Step 5: Analyze results
while (rset.next()) {
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Step 6: Release resources
try {
if (rset != null)
rset.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (stmt != null)
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
if (conn != null)
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
My database name is BookReservationDatabase, I use root as a login and password on PhpMyAdmin.
I have got the following errors :
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:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:990)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:342)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2188)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2221)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2016)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:776)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:386)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:330)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at features.JDBC.main(JDBC.java:26)
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:211)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:301)
... 15 more
The error must be among DBURL,DBLOGIN and DBPASSWORD. Because the code generate error at the connection
conn = DriverManager.getConnection(DBURL, DBLOGIN, DBPASSWORD);
java.net.ConnectException: Connection refused (Connection refused)
clearly signals a communication error on the machine on which you run this code. This could be caused by many reasons, thus I merely list the most likely ones:
MySQL is not running at all.
Did you start it? Verify by inspecting running process lists (depends on OS).
MySQL is not listening on Port 3306 which is the default port.
Did you change it? If so, change your code/config accordingly.
In case a firewall is active, check the rules that could prevent connections on port 3306.
Hope it helps.
I am having issues connecting to mySQL server using ConnectJ driver for JDBC.
I wrote a simple program just to establish connectivity as below:
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://[host]:1521/OBIEE11G";
private static final String DB_USER = "OBADW";
private static final String DB_PASSWORD = "OBADW";
public static Connection getConnection() {
Connection dbConnection = null;
try {
// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
try {
// DriverManager.registerDriver(new com.mysql.jdbc.Driver());
System.out.println("before get connection ***********");
System.out.println("Java version: " + System.getProperty("java.version"));
Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("JDBC driver: " + driver.getMajorVersion() + "." + driver.getMinorVersion());
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
System.out.println("Connection: " + dbConnection.getClass().getName());
System.out.println("after get connection ***********");
return dbConnection;
} catch (SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return dbConnection;
}
public static void main(String[] args) {
Connection dbConnection = getConnection();
if (dbConnection != null) {
System.out.println("Connected");
} else {
System.out.println("Failed");
}
I am getting the following error:
before get connection ***********
Java version: 1.7.0
JDBC driver: 5.1
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:85)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:57)
at java.lang.reflect.Constructor.newInstance(Constructor.java:541)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:983)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:628)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1014)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2254)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2285)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2084)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:85)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:57)
at java.lang.reflect.Constructor.newInstance(Constructor.java:541)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:226)
at JDBCConnection.getConnection(JDBCConnection.java:32)
at JDBCConnection.main(JDBCConnection.java:45)
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2949)
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:560)
... 17 more
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.
Failed
I am using connectJ : mysql-connector-java-5.1.37-bin.jar
Java 1.7, JDBC driver 5.1
I am able to ping the host, and connect it using mysql developer.
Please suggest.
From your log its clear about "Communications link failure"
ensure your mysql server running
ensure you have the right hostname/ip/port
ensure your network is working
Sounds stupid to ask but have you configured your MySQL Connector.jar file correctly in your project properties?
I am having connection issues with my java program interacting with oracle 11g using ojdbc7.jar. I am using jdk 1.8 on windows 7 platform. I'm getting an error with the connection.
I'm writing my whole program below:
package mydao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AdminDAO {
Connection con;
public void connectionMethod() {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:oracleEE", "system", "tiger");
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
public void loginCheck(String uid, String pwd) {
connectionMethod();
try {
String sql = "SELECT * FROM ADMIN_LOGIN WHERE ADMINUID=? AND ADMINPWD=?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, uid);
ps.setString(2, pwd);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
rs.getString(1);
rs.getString(2);
rs.getString(3);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
AdminDAO a = new AdminDAO();
a.loginCheck("avi", "avi3");
}
}
But I'm getting error like this:
run:
java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:673)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:715)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:385)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:30)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:564)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at mydao.AdminDAO.connectionMethod(AdminDAO.java:33)
at mydao.AdminDAO.loginCheck(AdminDAO.java:43)
at mydao.AdminDAO.main(AdminDAO.java:74)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:445)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:464)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:594)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:229)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1360)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:486)
... 9 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:162)
at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:411)
... 14 more
Exception in thread "main" java.lang.NullPointerException
at mydao.AdminDAO.loginCheck(AdminDAO.java:61)
at mydao.AdminDAO.main(AdminDAO.java:74)
Java Result: 1
Can anyone help me getting out of this problem? I'm confused how to recover from this error.
Please try to start the TNS-Listener service in services.msc.
It seems that the server is not listening on the specified port or hostname.
Check if your service is running and if so check the port on which it is listening. If your oracle service is listening in different port update the same in your code and check.
My code:
package staffrecords;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StaffRecords {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String databaseName = "SEGA";
//String loginUrl = "jdbc:mysql://localhost:3307/" + databaseName;
String loginUrl = "jdbc:mysql://dbprojects.eecs.qmul.ac.uk:3306/" + databaseName;
String user = "SEGA";
String password = "*****";
try
{
con = (Connection) DriverManager.getConnection(loginUrl, user, password);
st = (Statement) con.createStatement();
String sql;
sql = "SELECT StaffID FROM Staff";
rs = st.executeQuery(sql);
if (rs.next())
{
String staffID = rs.getString("StaffID");
System.out.print("StaffID: " + staffID);
}
rs.close();
st.close();
con.close();
}
catch (SQLException ex)
{
System.out.println(ex);
}
}
}
And the error is:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException
MESSAGE: Connection timed out: connect
STACKTRACE:
java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:241)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2771)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at staffrecords.StaffRecords.main(StaffRecords.java:28)
** END NESTED EXCEPTION **
Last packet sent to the server was 2 ms ago.
BUILD SUCCESSFUL (total time: 24 seconds)
Is there a simple solution to get the code to print out all the StaffID values in the table Staff?
I did a quick online port scan for that address and it looks like the server side is not listening on port 3306. Maybe firewall configuration? Or just stopped server/wrong address.
Looking like that Driver is throwing that
reason can be that
service not listening
Connections are not free
I am creating a simple example of jdbc .I am getting this error .I run my sql server on my mac machine .can you please tell me how to make connection with my sql and remove this error .I already include connector jar file .
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:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1129)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:358)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2489)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2311)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
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:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:347)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:207)
at HelloWorldExample.main(HelloWorldExample.java:17)
Caused by: java.net.UnknownHostException: local
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:877)
at java.net.InetAddress.getAddressFromNameService(InetAddress.java:1230)
at java.net.InetAddress.getAllByName0(InetAddress.java:1181)
at java.net.InetAddress.getAllByName(InetAddress.java:1111)
at java.net.InetAddress.getAllByName(InetAddress.java:1047)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:248)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:308)
... 15 more
Here is my code ..I am using mac
import java.sql.*;
/**
* HelloWorldExample : JDBC Tutorial that creates a simple database, stores in a single row
* and retrieves the data to then be displayed on standard out. The database is cleaned up
* to reduce clutter for this example.
* Author: Kevin Hooks
* Date: April 18th, 2012
**/
public class HelloWorldExample {
public static void main(String[] args) throws SQLException{
// Note that you can use TCP/IP by using this URL
// "jdbc:raima:rdm://localhost"
// The rdmsqlserver must be running to use TCP/IP
Connection Conn = DriverManager.getConnection("jdbc:mysql://local");
try {
Statement Stmt = Conn.createStatement();
try {
try { //Since the database is created here, it cannot be created twice
Stmt.execute("DROP DATABASE hello_db");
} catch (SQLException exception) {}
Stmt.execute("CREATE DATABASE hello_Db");
Stmt.execute("CREATE TABLE hello_table (f00 char(31))");
Conn.commit();
PreparedStatement PrepStmt = Conn.prepareStatement("INSERT INTO hello_table (f00) VALUES (?)");
try { //Sets parameter value to a string
PrepStmt.setString(1, "Hello World!");
PrepStmt.execute();
Conn.commit();
ResultSet RS = Stmt.executeQuery("SELECT * FROM hello_table");
try {
while(RS.next() != false) {
System.out.println(RS.getString(1));
}
} finally {
RS.close();
}
} finally { //Cleans up by dropping database in this case
Stmt.execute("DROP DATABASE hello_db");
PrepStmt.close();
}
} finally {
Stmt.close();
}
} catch (SQLException exception) {
System.err.println("SQLException: " + exception.toString());
}finally {
Conn.close();
}
}
}
The hostname of the loopback address is localhost, not local.
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 HelloWorldExample.main(HelloWorldExample.java:17)
Line 17:
Connection Conn = DriverManager.getConnection("jdbc:mysql://local");
Your program can not establish a connection to the database, be sure that you have your connection URL correct.
local, should be replaced by localhost, or 127.0.0.1
You should also note, that you never actually select a database to use.
you have declared wrong connection string. please modified it according to below rule
Connection Conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name");
your URL should be localhost then add the database name
have a look at this
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
public class JDBCExample {
public static void main(String[] argv) {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/mkyongcom","root", "password");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}