Cannot connect to MySQL database in Java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java Connecting to remote MySQL database
I'm trying to connect to MySQL database in Eclipse and Java using the following code:
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "RS";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
But, I get the following error:
MySQL Connect Example.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:186)
at Expertise.main(Expertise.java:57)

You need to add the mysql jdbc driver jar to your classpath.

Download the mysql-connector to a local directory from here http://www.mysql.com/products/connector/
Go to Eclipse and select your project by right clicking on it.
Then a pop-up menu will get displayed. In there look for the item
properties and select it.
The the properties window will appear, look for the item Java
Build-path on the left select it
Then on the right of the window you will see a button with the "add
library" caption. Click on it and Look for the .jar file that you
just downloaded.

Make sure that MySQL jar is on your class-path
Make sure you have the correct import in your class.

Related

Intellij Cannot find class in class path [duplicate]

This question already has answers here:
Where should the JDBC driver JAR files reside on a Tomcat deployment with a datasource?
(2 answers)
Closed 7 years ago.
So i followed all the steps listed in other posts to add mysql-connector-java-5.1.36-bin to my class path in intellij 12 and when i'm writing code intellij clearly sees it and lets me import it, but when I run the application inside of tomcat I get a ClassNotFoundException
Below are screen shots of my set ups and my code.
public void runLookUp(String s){
String url = "jdbc:mysql://localhost:3316/test";
String username = "java";
String password = "password";
System.out.println("Connecting database...");
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
try {
Connection connection = (Connection) DriverManager.getConnection(url, username, password);
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
}
I am aware that doing it in global libraries instead of my lib directory is bad form I did it originally there and moved it to global as an attempted fix to this issue and just haven't moved it back yet. Given that this seems to work for everyone else I assume its something in the way I have my tomcat deploying from intellij, any thoughts?
This has nothing at all to do with IntelliJ.
You need to put JDBC driver JARs in the Tomcat /lib folder, not in any project WEB-INF/lib.
Your code as written is still far from optimal:
Hard coded URL, driver class, and credentials make it difficult to change.
Username and password in plain text.
No JNDI lookup.
No connection pooling.

JDBC connection not happening [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 7 years ago.
Below is the code I used for jdbc connection
String dbUrl="jdbc:mysql://localhost:3306/mysql";
String user= "kumar";
String pwd="ratiol";
try (Connection connection = DriverManager.getConnection(dbUrl, user, pwd)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
but I got error as below-
Exception in thread "main" java.lang.IllegalStateException: Cannot connect the database!
at jdbcConnection.Jdbcdemo.main(Jdbcdemo.java:22)
Caused by: java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mysql
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at jdbcConnection.Jdbcdemo.main(Jdbcdemo.java:19)
Can you please tell me how can I get jdbc url?
I am using eclipse(mars) in ubuntu 14.04
if you are using netbeans, right click project -->properties -->libraries-->add library and select MySQL JDBC Driver
just add the com.mysql.jdbc.Driver to the lib folder in you program files.
This is what you wrote
try (Connection connection = DriverManager.getConnection(dbUrl, user, pwd)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
it would be like this:
Connection con = null;
try {
//registering the jdbc driver here, your string to use
//here depends on what driver you are using.
Class.forName("something.jdbc.driver.YourFubarDriver");
Connection connection = DriverManager.getConnection(dbUrl, user, pwd)
} catch (SQLException e) {
throw new RuntimeException(e);
}
Please check Class.forName not more needed when using JDBC v.4
Let's take a quick look at how we can use this new feature to load a
JDBC driver manager. The following listing shows the sample code that
we typically use to load the JDBC driver. Let's assume that we need to
connect to an Apache Derby database, since we will be using this in
the sample application explained later in the article:
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
Connection conn =
DriverManager.getConnection(jdbcUrl, jdbcUser, jdbcPassword);
But in JDBC 4.0, we don't need the Class.forName() line. We can
simply call getConnection() to get the database connection.
Note that this is for getting a database connection in stand-alone
mode. If you are using some type of database connection pool to manage
connections, then the code would be different.
There are plenty of reason for the exception No suitable driver found for jdbc:mysql like
Your JDBC URL can be wrong.
ClassPath/BuildPath/Lib folder missing the connector jar.
Driver Information is Wrong.
Just load the driver first:
Class.forName("com.mysql.jdbc.driver");

SQL Connection problems (Wrong url?) [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 7 years ago.
So I was testing out MySQL databases for the first time, (For the following code, all I want to do is establish a connection to the data base):
import java.sql.*;
public class Driver {
public static void main(String[] args) {
Connection con = null;
try{
String url = "jdbc:mysql://localhost:3306/movie";
String user = "root";
String pw = "RockoAndLuke739969";
con = DriverManager.getConnection(url, user, pw);
}
catch(SQLException e){
e.printStackTrace();
}
}
}
And here is the Exception:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/movie
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Driver.main(Driver.java:13)
And I don't know why it isn't working.... thanks for taking your time to read :)
(I am new to stackoverflow by the way, so sorry if I screwed something up xD)
You need to add the driver in your classpath.
If you are using maven you have to add the following dependency
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
If you aren't using maven check your classpath manually and add the driver to it.
In addition add
Class.forName("com.mysql.jdbc.Driver").newInstance();
as first line of your connection code. This line is needed to load the class driver and is used by DriverManager to know wich driver must be used.
Here the reference documentation link

Can't Connect To Remote Oracle Database (11g)

I'm trying to connect a linux machine which has oracle database 11gr2 setup inside. There is no problem with connecting PL/SQL developer with any user. Unfortunately, with my simple java application, it's impossible to connect to database.
Here is my java code:
JAVA CODE
package oraConn;
import java.sql.*;
public class OraConn {
public static void main(String[] args) {
Connection connection=null;
try {
String driverName= "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
String serverName="192.168.2.122";
String portNumber="1521";
String sid="sas";
String url="jdbc:oracle:thin:#" + serverName + ":" + portNumber +":"+sid;
String userName = "system";
String password = "welcome";
connection = DriverManager.getConnection(url,userName,password);
} catch (Exception e) {
e.printStackTrace();
}
}
}
When i run this codeblock, i get an exception like this:
java.sql.SQLException: IO Error: Connection refused
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:489)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:553)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:254)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:528)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at oraConn.OraConn.main(OraConn.java:16)
Caused by: oracle.net.ns.NetException: Connection refused
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:399)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1140)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:340)
... 7 more
I am sure that port 1521 is open because i can use PL/SQL developer. What should i do?
Start your program in a debugger and copy the value of url. If you cannot connect with that URL using PL/SQL developer, something with your setting up the url is wrong. Change your program to get the same URL as in your working PL/SQL developer connection, and you should be done.
(This might sound simple, but it worked for me last time I had this problem).

Java won't connect to my database

Here's my code:
import java.sql.*;
public class DBConnector {
private static Connection conn;
public static void connectToDB()
{
//load the driver
try
{
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println ("Driver successfully loaded");
}
catch (ClassNotFoundException c)
{
System.out.println ("Unable to load database driver");
}
//connect to the database
try
{
String filename = "TopYouTubeVideos.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database += filename.trim () + ";DriverID=22;READONLY=true}";
conn = DriverManager.getConnection (database, "", "");
System.out.println ("Connection database successfully established");
}
catch (Exception e)
{
System.out.println ("Unable to connect to the database");
}
}
The output is:
Driver successfully loaded
Unable to connect to the database
This has worked on a different computer than mine, connecting to the database through exactly the same code... does anyone have any idea why?
Thanks in advance :)
EDIT: I'm running Access 2007, Windows 7 64bit
By checking for the error, I get: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
From a little bit of research it seems this is a problem with my 'data source name'. I put my database file in the project folder, and the name is correct. Why is it not finding it?
EDIT: No, the database was the same on both computers. In the same folder as well.
EDIT: I think I may need to create a system dsm. Following the instructions on the internet dosent work though, because I dont have the same files as them..
EDIT: I've tried to install that but it hasn't made a difference. My version of access is 64 bit alongside my version of netbeans..
Try installing a database engine + JVM that are both running in the same archeticture (i.e. 32bit), otherwise, you would receive a mismatch exception. I assume your JVM is 64bit but your database engine is not, so try installing a 64bit engine from the following link:
http://www.microsoft.com/en-us/download/details.aspx?id=13255

Categories

Resources