Connect to MySQL with JDBC driver

Here’s an example to show you how to connect to MySQL database via a JDBC driver. First, get a MySQL JDBC driver from here –MySQL JDBC Driver Download Here.

1. Java JDBC connection example

Code snippets to use a JDBC driver to connect a MySQL database.


Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
conn.close();

See a complete example below :

JDBCExample.java

package com.mkyong.common;

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!");
	}
  }
}

2. Run it

Assume JDBCExample.java is store in c:\test folder, along with the MySQL JDBC driver


C:\test>java -cp c:\test\mysql-connector-java-5.1.8-bin.jar;c:\test JDBCExample
-------- MySQL JDBC Connection Testing ------------
MySQL JDBC Driver Registered!
You made it, take control your database now!

C:\test>

P.S To run this example, your need mysql-connector-java-{version}-bin.jar in your classpath.

Done.

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
casiana
Guest
casiana

MySQL JDBC Connection Testing ————

MySQL JDBC Driver Registered!

Connection Failed! Check output console

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.(MysqlIO.java:358)

at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2498)

at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2535)

at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2320)

at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:834)

at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:46)

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:185)

at my.Connect.main(Connect.java:32)

Caused by: java.net.ConnectException: Connection refused: connect

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:366)

at java.net.Socket.connect(Socket.java:529)

at java.net.Socket.connect(Socket.java:478)

at java.net.Socket.(Socket.java:375)

at java.net.Socket.(Socket.java:218)

at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)

at com.mysql.jdbc.MysqlIO.(MysqlIO.java:308)

… 15 more

ddwwww
Guest
ddwwww

u have to comment out the bind_address = 127.0.0.1 by adding a # in front of it.

viroth
Guest
viroth

Helpful, Thank you sir.

guru prakash
Guest
guru prakash

Thanks, Helpful post

Wuod Okoth
Guest
Wuod Okoth

thank u

now how do i use it in struts 2 to insert

Roque Folminar
Guest
Roque Folminar

thank you so much for this article.
Can I also apply this connection to my SQL mail database connecting a ticketing system that requires connection to SQL? Please advise . Thank you.

Chandranshu Badoni
Guest
Chandranshu Badoni

connection failed:[HY000][MYSQL] [ODBC 5.2(w)Driver] access denied for ‘root’ @localhost’

while creating the data source on ODBC data source administrator …I face this problem

Erick Alves dos Santos
Guest
Erick Alves dos Santos

Why is it important using these statements?:

try {
Class.forName(“com.mysql.jdbc.Driver”);
} catch (ClassNotFoundException e) {
System.out.println(“Where is your MySQL JDBC Driver?”);
e.printStackTrace();
return;
}

Is it just to test?

Eric
Guest
Eric

Yes it is important in the way you can test the presence of the DB Driver. If it is not present, you can properly output a message for the user “I am sorry, you want me to connect to this f… DB, but I don’t even have the driver. I can’t go on the script!” ;-)

obloodyhell
Guest
obloodyhell

Try/catch are important. You should learn and understand the use of these, they are a very important part of modern event-driven programming, and, in some ways, one of the more problematic, as they lead to code which is very non-linear in nature (and thus much harder to debug). But you need to understand them — along with object-oriented concepts, they cannot be underestimated as to their importance to understanding how to program.

Tyagi
Guest
Tyagi

how to connect android app to sql server database……

Tyagi
Guest
Tyagi

i’m beginner in android so i m made a android apps to connect sql server so plzzz help me ..

mumu
Guest
mumu

Thanks for your help. It’s really helpful !

mani
Guest
mani

How to set jdbc classapth permanently

Markus Aurelius
Guest
Markus Aurelius

OMG!! After searching the internet for 6 Hours it stranded upon this. It is not like i don’t know how to use Google.
But i was looking for any tutorial that does JDBC connection without using ANY IDE.

Actually i have a case where i don’t have any IDE, all i have is JDK and Notepad. I had to search a lot to find how to “install” or where to put this JDBC driver Jar file. Phew helped a lot. Thanks.

technofranchise
Guest
technofranchise

Your articles are always best and easier to understand. The quality that brings the visitors is the simplicity and to the point talk. I was looking for the database connectivity using Java with NetBeans and I have arrived at the right place

Somnath Jagtap
Guest
Somnath Jagtap

Thanks ,
this is very useful code for java beginner

Felix
Guest
Felix

This null check is useless:

if (connection != null)

Reason: DriverManager.getConnection(..) either returns a not null connection or fails with an exception. See method implementation:

if (con != null) {
// Success!
println(“getConnection returning ” + aDriver.driver.getClass().getName());
return (con);
}

.. throw ..

Johny
Guest
Johny

Helpful post . But to understand how these interfaces of drivers works, one should read a bit about interfaces also. I found a link for interface here javaandme.com/core-java/interfaces . Hope it will be useful.

Jay
Guest
Jay

Hi mkyong,

I am facing the com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
issue in JBoss 7.1.1+Spring 3+Hibernate, Please share if you resolved this problem or any suggestions

Thanks
Jay

casiana
Guest
casiana

how do i connect first to database? pls help

ricardobarbosa
Guest
ricardobarbosa
Hi, i trying test the follow environment, but not worked. In emulator display message “No suitable Driver”, I using mysql connector 5.1.27. My code package com.example.androidmysql; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import android.os.Bundle; import android.widget.TextView; import android.app.Activity; import android.database.*; public class AndroidMysql extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final TextView codigo = (TextView) findViewById(R.id.codigo); final TextView nome = (TextView) findViewById(R.id.nome); final TextView email = (TextView) findViewById(R.id.email); try { Connection conexao = DriverManager.getConnection(“jdbc:mysql://192.168.3.112/banco”, “java”, “123456”); Statement stm = conexao.createStatement(); ResultSet rs = stm.executeQuery(“SELECT id, nome, email FROM alunos”); while… Read more »
Sanisa
Guest
Sanisa

Thanks A Lot. This is help me lot

AlexFromRussia
Guest
AlexFromRussia

Maybe jdbc:mysql://hostname:port//dbname”,”username”, “password” ?
Need two // !

Kumail Haider
Guest
Kumail Haider

Hello. I have my java project in eclipse that has an sql connection with a database and is working fine. I want to export my project as a runnable jar but after exporting the connection doesnt work. Could you please advise how can I export my project with the connection intact please? thanks.

Code Nirvana
Guest
Code Nirvana

Hello!
I did this but getting some error, than i got the error i.e., Adding MySQL-JDBC Driver to the project which is very **IMPORTANT**..
I gave a try to write on the topic: Adding MySQL JDBC Driver Library In NetBeans:
http://www.codenirvana.in/2013/04/adding-mysql-jdbc-driver-library-in.html

-Thanks!

Son Nguyen Thanh
Guest
Son Nguyen Thanh

Hi Mkyong.
From your sentence: “P.S To run this example, your need mysql-connector-java-{version}-bin.jar in your classpath”
==> You mean that copy the “mysql-connector-java-{version}-bin.jar” into your classpath.
Is it right?
Id yes, could you tell us how to identify the classpath. Thanks.

Noman
Guest
Noman

How can i use JDBC with MYSQL in a JSP page ??
Can you explain that ??

Tudy
Guest
Tudy

hi.. can u make same tutorial for android ?
thank you for all tutorials

Sajjad
Guest
Sajjad

Hi Mr yong,

I try this test, But i don’t have mysql-connector-java-{version}-bin.jar file.
I use netbeans 7.2.1 for this,

How fix problem?

Thanks

programmer
Guest
programmer

Mr Sajjad, you just need to add mysql driver from NetBeans IDE library…

elahe
Guest
elahe

i get this error when run it:
——– MySQL JDBC Connection Testing ————
MySQL JDBC Driver Registered!
Connection Failed! Check output console
java.sql.SQLException: Communication link failure: java.io.IOException, underlying cause: Unexpected end of input stream

** BEGIN NESTED EXCEPTION **

java.io.IOException
MESSAGE: Unexpected end of input stream

STACKTRACE:

java.io.IOException: Unexpected end of input stream
at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:1096)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:626)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1562)
at com.mysql.jdbc.Connection.(Connection.java:491)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at vo.Test.main(Test.java:87)

** END NESTED EXCEPTION **

at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:699)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1562)
at com.mysql.jdbc.Connection.(Connection.java:491)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at vo.Test.main(Test.java:87)

i really dont now why this error occured?please help me

Anonymous
Guest
Anonymous

Hi, Elahe!
Are you using some IDE such as Eclipse or NetBeans??

trackback
Portofoilo » Blog Archive » Code to connect Java to mysql

[…] Source:¬†http://www.mkyong.com/jdbc/how-to-connect-to-mysql-with-jdbc-driver-java/ […]

Abhishek
Guest
Abhishek

You are doing awesome and I have learnt a lot from your tutorials