Can't connect to a mysql DB with DriverManager - java

Ok I am trying to connect to a mysql db with the following code. I tried looking at documentation but I am just having no luck what so ever.
Here is the code:
public class TESTSQL {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://SLibraryDev.db.996****.hostedresource.com";
static final String USER = "SLD";
static final String PASS = "F11!";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_DRIVER);
// STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
...
}
This is the error I am getting :
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
When I comment out "Class.forName(JDBC_DRIVER)" and run it I get this error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://SLibraryDev.db.996****.hostedresource.com
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
What I thought I needed to do was to download and run this : http://dev.mysql.com/downloads/connector/j/ which I did but it seemed like something was wrong with this installer...It seemed like it never finished, like it cut out in the middle of the process. Anyone have any ideas on what I need to do.

Download mysql-connector from following url
http://nearbuy.googlecode.com/files/mysql-connector-java-5.1.13-bin.jar
and add it to your class path.
If you are using netbeans, to add this file to your project do followoing
Right click on your project>click libraries>click add JAR/Folder> then select downloaded jar file

You need to download the mysql jdbc driver jar and include it in your classpath

java.sql.SQLException: No suitable driver found for jdbc:mysql://SLibraryDev.db.996****.hostedresource.com
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
clearly suggests that there is no driver in your class path
simply add the mysql driver jar file in to class path

Related

Communications link failure when connecting to remote MySQL database

I'm trying to make a Java program communicate with a MySQL server hosted with A Small Orange. The IP and port they provided me with are 129.121.106.234:3306. The user has been given full permissions to the database, and in my CPanel I've allowed all remote hosts to connect to the MySQL database by adding the access host "%".
I'm using Eclipse, and I've downloaded and added the JDBC driver to the build path.
As near as I can tell, the user I'm trying to use has full permissions to the database, and the MySQL server is open to any request from any IP. I've also tried my admin MySQL credentials, with the same error, so I'm decently confident the issue is with my code. Not absolutely sure though, since I'm not hosting the MySQL server myself.
My code:
package com.package.IPBounce;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* Isaac the Support Ninja says: The MySQL port is 3306. The IP you use
* is 129.121.106.234.
*/
URL whatismyip;
String IP;
try {
whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
whatismyip.openStream()));
IP = in.readLine();
System.out.println(IP);
Connection con = null;
Statement st = null;
ResultSet rs = null;
//this is just testing code until I get the connection working
String url = "jdbc:mysql://129.121.106.234:3306/db_name";
String user = "user_name";
String password = "small_password";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, user, password);//error is on this line
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The error text:
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(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1137)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:356)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2504)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2541)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2323)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.package.IPBounce.Main.main(Main.java:39)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:258)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:306)
... 15 more
Edit: I found the solution. My hosting service was blocking the MySQL requests at the firewall. Cleared that up, now it works wonderfully.
The only thing I see as a possible issue is the "newInstance()" call. Try remove that and see if that works.
From:
Class.forName("com.mysql.jdbc.Driver").newInstance();
To:
Class.forName("com.mysql.jdbc.Driver");
This question has been answered here:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
Please try the steps in the accepted answer and see if your issue is resolved.
From my experience, I had this issue when my MySql configuration file allowed only localhost access. Replace localhost with the ip address.

Sqoop from within a Java program

I have read the questions on using Sqoop from within a Java program here, here and here.
I came up with the following, but I am stumped by a ClassNotFoundException:
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import com.cloudera.sqoop.SqoopOptions;
import com.cloudera.sqoop.SqoopOptions.FileLayout;
import com.mysql.jdbc.*;
public class SqoopExample {
public static void main(String[] args) throws Exception {
String driver = "com.mysql.jdbc.driver";
Class.forName(driver);
Configuration config = new Configuration();
// note that this is HDFS path, rather than core path
config.addResource(new Path("./config/core-site.xml"));
config.addResource(new Path("./config/hdfs-site.xml"));
FileSystem dfs = FileSystem.get(config);
SqoopOptions options = new SqoopOptions();
options.setDriverClassName(driver);
options.setConnectString("jdbc:mysql://localhost:3306/dbname");
options.setTableName("v_webstats");
options.setUsername("root");
options.setNumMappers(1);
options.setTargetDir(dfs.getWorkingDirectory()+"/TestDirectory");
options.setFileLayout(FileLayout.TextFile);
new com.cloudera.sqoop.tool.ImportTool().run(options);
}
}
I am sure that all the jars are correctly included and I have tested the connection to my database server and that works as well.
The exact error is:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at SqoopExample.main(SqoopExample.java:14)
not sure what I am doing wrong.
I believe that proper name of the MySQL JDBC driver class is:
com.mysql.jdbc.Driver
(notice the capital "D" in the "Driver)

Error in connecting oracle 11G in localhost using JDBC

import java.sql.*;
public class one {
public static void main(String[] args)
{
Connection conn=null;
Statement stmt=null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:#//localhost:1521/ecom","system","manager");
stmt=conn.createStatement();
String str="insert into country values(3,'bangladesh');";
int k=stmt.executeUpdate(str);
System.out.println(k);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The only jar file I added to the class path is ojdbc6.jar is there any other jar required for connecting with oracle 11g(11.2.0.1.0) I am using eclipse as IDE
here are the errors
java.sql.SQLException: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:412)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:531)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:221)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:503)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at one.main(one.java:17)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:359)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:422)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:672)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:237)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1042)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:301)
... 7 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocket`Impl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:141)
1) Please be sure database host name, port number, or database instance name are correct.
2) Be sure the TNSListener has been started ( run lsnrctl start)
The connection string is malformed. It should be
"jdbc:oracle:thin://#localhost:1521/ecom"
Notice the transposition of // and #.

MySQL jdbc driver and Eclipse problems

I am having problems loading the MySQL JDBC driver. I have tried everything mentioned here, but am still running into problems.
The error I get is this:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Main.main(Main.java:12)
My code is as follows:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Main {
public static void main(String args[]) throws Exception {
//accessing the driver
Class.forName("com.mysql.jdbc.driver");
// creating variable to pass the connection information into
Connection dbcon = DriverManager.getConnection(
"jdbc:mysql//localhost:3306/test", "root", "root");
PreparedStatement statement = dbcon
.prepareStatement("select * from names");
ResultSet result = statement.executeQuery();
while (result.next()) {
System.out.println(result.getString(2));
}
}
}
As you can see above I have placed the driver in the lib folder and I have also put it into the Apache tomcat lib folder, because that was suggested as well.
Thank you for any help you can give me.
Andrew
The class name inside the MySql connectorJ JAR file is Driver. so you need to change
Class.forName("com.mysql.jdbc.driver");
to
Class.forName("com.mysql.jdbc.Driver");
It tells you the problem on the first line of your stacktrace:
Exception in thread "main" java.lang.ClassNotFoundException: com.mysql.jdbc.driver
The driver name is com.mysql.jdbc.Driver (capital D).
problem in loading the mysql connection library.please check the proper mysql library is load successfully.because when library load successfully then the library package display all the external loaded library.

java connectivity with mysql error

I just started with the connectivity and tried this example. I have installed the necessary softwares. Also copied the jar file into the /ext folder.Yet the code below has the following error
import java.sql.*;
public class Jdbc00 {
public static void main(String args[]){
try {
Statement stmt;
Class.forName("com.mysql.jdbc.Driver");
String url =
"jdbc:mysql://localhost:3306/mysql"
DriverManager.getConnection(url,"root", "root");
//Display URL and connection information
System.out.println("URL: " + url);
System.out.println("Connection: " + con);
//Get a Statement object
stmt = con.createStatement();
//Create the new database
stmt.executeUpdate(
"CREATE DATABASE JunkDB");
stmt.executeUpdate(
"GRANT SELECT,INSERT,UPDATE,DELETE," +
"CREATE,DROP " +
"ON JunkDB.* TO 'auser'#'localhost' " +
"IDENTIFIED BY 'drowssap';");
con.close();
}catch( Exception e ) {
e.printStackTrace();
}//end catch
}//end main
}//end class Jdbc00
But it gave the following error
D:\Java12\Explore>java Jdbc00
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at Jdbc00.main(Jdbc00.java:11)
Could anyone please guide me in correcting this?
The jar file that contains the MySQL driver class (com.mysql.jdbc.Driver) isn't being found on the classpath when you run your application. This is what the ClassNotFoundException is complaining about.
You'll need to add it either to the CLASSPATH environment variable, or using the classpath option when running Java. For example:
java -cp mysql-connector-java-5.0.8-bin.jar Jdbc00
Use the name and location of whatever MySQL connector jar file you're using. (If you haven't already installed MySQL on localhost, so your application has something to connect to, you might have to do that too.)
As #Ash says, the problem is that the Connector/J drivers are not on your classpath. You can download the latest version (5.0.12) from this page.

Categories

Resources