Java to Database Connection : Exception - java

I am connecting my java program to mysql database. But i get an exception block executed instead of getting connected i.e, "Connection Failed!!".
import java.sql.*;
public class Mysqltest
{
public static void main(String args[])
{
String username ="root";
String password ="bharath12";
String url ="jdbc:mysql://localhost:3307/";
String dbName = "sample";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
try
{
Class.forName(driver).newInstance();
con=DriverManager.getConnection(url+dbName, username, password);
System.out.println("Connection successfully established.");
con.close();
System.out.println("Connection terminated !");
}
catch(Exception e)
{
System.out.println("Connection failed !!");
}
}
}
What would be the error in the above code?
I deliberately changed mysql port to 3307 during installation (hence, localhost:3307)

You should not have additional space only separator allowed is in classpath variable for windows is ;
So your CLASSPATH variable should be like below-
C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;C:\Program Files\Java\jdk1.7.0_07\lib\mysql-connector-java-5.1.22-bin.jar;
There is a space in your class path before mysql jar.
Moving ahead it is advisable to use class path with -cp option rather than global CLASSPATH since global class path has precedence over application class path it can create problems if there are same classe names in different jar which is mentioned in Global Classpath.
You can also start using editor like Eclipse in which you can simply add required jar files in build path.

Related

How to establish connection between Java Program and Database without using IDE/ External Tools?

I want to write a Java Program for Establishing Connection between Java Program and Database, but I don't want to use any IDE like Netbeans, Eclipse, Visual Studio, XAMP, etc. I have jar files for Driver of required DBMS.
public class JDBCDemo
{
public static void main(String args[])
{
try
{
/**
* Steps for Establishing Connection between Java Application and Database
*/
//1. Load and Reginster Driver
Class.forName("com.mysql.jdbc.Driver");
//2. Establish a connection between Java Application and Database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/practicals", "root", "root123");
//3. Create Statement Object
Statement st = con.createStatement();
//4. Send and Execute SQL queries
ResultSet rs = st.executeQuery("SELECT * FROM tushar");
//5. Process the result from ResultSet object
while(rs.next())
{
System.out.println(rs.getString(1));
}
//6. Close the Connection
con.close();
}
catch(Exception e)
{
System.out.println(e.toString().trim());
}
}
}
It is showing error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
How to Establish connection ??
You need to add the mysql driver jar in the classpath before you run the program.
There are various ways to do so.
javac -cp "JAR_PATH" ClassName.java
java -cp "JAR_PATH" ClassName
Add the jar file in C:\Program Files\Java\\jre\lib\ext
set classpath=PATH_TO_JAR;
colon(:) is compulsory after jar file name
Compilling Program
javac -cp mysql-connector.jar: ProgramFileName.java
javac -cp mysql-connector.jar: JDBCDemo.java
Running Program
java -cp mysql-connector.jar: ProgramFileName
java -cp mysql-connector.jar: JDBCDemo
Note:- Simillar can be applied while using other jar files for performing other operations.
Sample Output

JDBC no suitable driver found just on Linux? [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed last month.
I am trying to write a program to connect to a MySQL database in eclipse, but I get the error "java.sql.SQLException: No suitable driver found".
The java code is:
import java.sql.*;
public class FirstExample {
//static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String S_DB_URL = "jdbc:mysql://localhost:3306/emp";
static final String S_USER = "root";
static final String S_PASS = "root";
public static void main(String[] args) {
try {
System.out.println("Connecting to database...");
//Class.forName(S_JDBC_DRIVER);
Connection connection = DriverManager.getConnection(S_DB_URL,
S_USER, S_PASS);
System.out.println("Creating statement...");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM Employee";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int iId = resultSet.getInt("id");
int iAge = resultSet.getInt("age");
String sFirst = resultSet.getString("fname");
String sLast = resultSet.getString("lname");
System.out.print("ID: " + iId);
System.out.print("\tAge: " + iAge);
System.out.print("\tFirst: " + sFirst);
System.out.println("\tLast: " + sLast);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
for (Throwable t : se) {
t.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
The output in the console tab is:
Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/emp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at FirstExample.main(FirstExample.java:21)
Goodbye!
I have used the MySQL Connector/J. It is unzipped in the MySQL installation directory and the jar file is added to the CLASSPATH.
Also refer to this image. There is an ! mark at the project root.image01
I get the error as in the next image: image02 when I include the 2 commented statements:
static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);
For all but the most trivial applications the CLASSPATH environment variable is NOT used. Normally the libraries are include in the Class-Path entry in the manifest of the jar, or in the -cp option of the java commandline.
In this case you need to add the MySQL JDBC driver to the buildpath of your Eclipse project.
I had the same problem. I solved it by adding:
Class.forName("com.mysql.jdbc.Driver");
you can place the path like java -cppwd/mysql-connector-java-5.1.22-bin.jar:. <classname>.
make sure that your in same directory where the mysql driver is .
Hope that helps .
Load Driver class just before getting the connection.
Use this code:
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_db", "user", "passw");
Alternatively you can also add the installed jar file to your eclipse project by selecting the project in eclipse, right click it and go down to properties, select the Java Build Path>>select the Libraries Tab>>Add external jar file and browse for the installed mysql-connector-java.jar file or any mysql java connector file int the /usr/share/java/ directory for most ubuntu users. Click okay and rebuild your project. Good luck
I encountered the same problem as you, but I handled it as follows:
I copied the jar, which is called mysql-connector-java-5.1.23-bin.jar, into the \Apache Software Foundation\Tomcat 6.0\lib, and restarted tomcat.
Hope that helps

Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I wanted to print the contents in a database but whenever I run this program I got this error saying that
Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mydatabase
I have installed MySQL from this link http://dev.mysql.com/downloads/windows/installer/ its a 248mb file and installed completely. I can access my database within MySQL but can't able to access from netbeans. I separately downloaded the mysql-connector-java-5.1.4.jar and set the CLASSPATH but now also I got this error.
import java.sql.*;
public class jdbcResultSet {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydatabase","root",
"root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM employee");
System.out.println("id name job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
}
catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}
First Check can you import import com.microsoft.sqlserver.jdbc.SQLServerDriver;
if it say com.microsft can not be resolved to a type that means u have to add your jar files to java build path and after that to deployment path from project properties.
java build path
Right click on project=>Properties=>Java Build Path=>
Librariess=>ADD External Jar file
deployment path
Right click on project=>Properties=>Deployment Assembly=>
ADDs=>Java Build Path Entries==> mssql_jdbc
The CLASSPATH environment variable is only used by the java.exe command and even then only when used without any of the -cp, -classpath, -jar arguments. It is ignored by IDEs.
So if you are running the application from your IDE place the mysql-connector.jar in your IDE's classpath
I downloaded the mysql-connector-java-5.1.4.jar file and placed in "C:\Program Files\MySQL\Java Connector" directory and edit System Environment Variable from control panel then set CLASSPATH as C:\Program Files\MySQL\Java Connector
Add the jar file, not the directory that the jar file is in.
Instead of,
C:\Program Files\MySQL\Java Connector
the CLASSPATH should include,
C:\Program Files\MySQL\Java Connector\mysql-connector-java-5.1.4.jar

Connecting to a mySQL database using Java

So I just started learning about databases this week and one of the things I need to be able to do is connect to my mySQL database that I created using Java. I have done some research and I have tried to find the correct way of doing this I just can't seem to figure out how. Here is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Menu
{
public void menu()
{
Connection conn;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "gym";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "password";
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)
{
System.out.println("NO CONNECTION =(");
System.out.println(e.getMessage());
}
}
}
Now the problem is, is that every time I run this code, the "No Connection =( " appears and then it says the error is: "com.mysql.jdbc.Driver". Can somebody please help me and say what I am doing wrong? Thank you. Much appreciated.
Your error means that your library path doesn't contain the jar that contains the com.mysql.jdbc.Driver class.
You don't have to change anything in your code. If you are running it via Eclipse, you should add mysql-connector-java-x.x.x-bin.jar to your build path (where x.x.x is the version of the jar).
All JDBC connection classes need their respective drivers which are normally supplied as jar files from the database vendor, add the relevant database driver to your classpath.
The .jar file will be available from the vendors site, in this case : http://www.mysql.com/products/connector/ and then to add this to the classpath of your project in the ide of your choice. Here is a guide for eclipse : http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-(Java)
Try and run again once you have this.

how to link java and mysql

I created a database from the command line and wrote Java code to access the database. My code prints an error on execution. Can anyone tell me how to connect the JDBC driver with Java?
import java.sql.*;
class Test{
public static void main(String arg[]){
try{
String query="select * from photo ";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/mydb","user","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
rs.next();
String sname=rs.getString(2);
System.out.println(sname);
con.close();
}
catch(Exception e)
{
System.out.println("error ");
}
}
}
First of all remove the space at the end of the query
String query="select * from photo ";
Next try giving the port in the url
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
Finally as you said its giving you java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
you need to add the mysql-connector.jar in your classpath.Get the jar from here
Well if you are using command prompt you can run like this
java -cp .;completePathOfMysqlConnector/mysql-connector-java-5.1.6.jar className
If you are using elipse then download the jar and add it to the classpath like this
Right click on the project -> properties ->java build path ->switch to libraries tab -> add external jar then select the jar and ok you are done
1>it seems that SQL port is not assigned (default is 3306) in "jdbc:mysql://localhost"
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
2> should download and add mysql-connector-java to library
Hope this would help

Categories