Home Jdbc Jdbc-mysql Connecting to a MySQL Database in Java
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Connecting to a MySQL Database in Java

Advertisement
In java we have been provided with some classes and APIs with which we can make use of the database as we like. Database plays as very important role in the programming because we have to store the values somewhere in the back- end.

Connecting to a MySQL Database in Java

     

In java we have been provided with some classes and APIs with which we can make use of the database as we like. Database plays as very important role in the programming because we have to store the values somewhere in the back- end. So, we should know how we can manipulate the data in the database with the help of java,  instead of going to database for a manipulation. We have many database provided like Oracle, MySQL etc. We are using MySQL for developing this application. 

In this section, you will learn how to connect the MySQL database with the Java file. Firstly, we need to establish a connection between MySQL and Java files with the help of MySQL driver .  Now we will make our  account in MySQL database so that we can get connected to the database. After establishing a connection  we can access or retrieve data form MySQL database. We are going to make a program on connecting to a MySQL database, after going through this program you will be able to establish a connection on your own PC.

Description of program:

This program establishes the connection between MySQL database and java files with the help of various types of APIs interfaces and methods. If connection is established then it shows "Connected to the database" otherwise it will displays a message "Disconnected from database".

Advertisement

Description of code:

Connection:
This is an interface in  java.sql package that specifies connection with specific database like: MySQL, Ms-Access, Oracle etc and java files. The SQL statements are executed within the context of the Connection interface.

Class.forName(String driver):
This method is static. It attempts to load the class and returns class instance and takes string type value (driver) after that matches class with given string.

DriverManager:
It is a class of java.sql package that controls a set of JDBC drivers. Each driver has to be register with this class.

getConnection(String url, String userName, String password):
This method establishes a connection to specified database url. It takes three string types of arguments like: 

    url: - Database url where stored or created your database
  userName: - User name of MySQL
  password: -Password of MySQL 

con.close():
This method is used for disconnecting the connection. It frees all the resources occupied by the database.

printStackTrace():
The method is used to show error messages. If the connection is not established then exception is thrown and print the message.

Here is the code of program:

import java.sql.*;

public class MysqlConnect{
  public static void main(String[] args) {
  System.out.println("MySQL Connect Example.");
  Connection conn = null;
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "jdbctutorial";
  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();
  }
  }
}

Download this example.

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 13, 2007

Ask Questions?    Discuss: Connecting to a MySQL Database in Java   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
Adrian
March 31, 2011
Thanks

Thanks for this tutorial. I was completely at a loss as to how to establish the connection in the first place, and this has been a huge help. :-) Now to get on with writing the queries...
speeddaemon
April 8, 2011
problem in code

hey, you haven't specified the parameter's for passing the sql queries....
swatantra mishra
April 13, 2011
Connecting to a MySQL Database in Java

give me the ans
R.Shivaraja
April 19, 2011
java

how to save JDBC program and what is the procedure to load the project in NET Beans IDE
deep prakash
June 4, 2011
engineering

creating jdbc
Johnydep
June 13, 2011
Question about mySQL jdbc driver

I am using eclipse. Whenever i try to run, i get an exception. I heard i have to copy the jar file somehwere and set the classpath. How can i do that?
VIVEK
July 28, 2011
Help me

What are the procedure to make a connection between java and mysql in control panel.
Akshita
August 16, 2011
nothing

happy birth daY
eugene
June 11, 2013
connecting to mysql database in java

I always get an error of "No suitable driver found for jdbc:msql://localhost:3306/test" whenever i try running my code even after adding the mysql-connector-java jar file to my libraries.Any one got an idea what the problem might be?
Deepak Kumar
June 12, 2013
My SQL Driver

Hi, Download the mysql driver from mysql.com and include it in your project. Thanks
vivek kushwaha
August 24, 2011
Advance java

thanks for give me this connectivity i like this site it is complet. i am fully satisfied.
Ganesh
August 25, 2011
server.?

Do this need a server to run this simple application?
AA
September 9, 2011
Thank you

This has been a great help, Thank you very much for your post!
poonam
September 17, 2011
servlet

thank you
Akhil P M
October 6, 2011
unable to connect

i tried this code & i got a ClassNotFoundException.i had mysql installed on my system(mysql Ver 14.14 Distrib 5.1.41) & i uses eclipse for java coding.Please tell me how can i get a connection to DB? whether any additional installation is needed for to get the connection(in Ubuntu)?
Rajendra Verma
November 24, 2011
jdbc

I love this 4 hour se paresan tha
shishir
December 5, 2011
Note for you

Please remember that we need to add sql-connector.jar to enable all this code.
Ashutosg
December 17, 2011
connectivity

i m not understanding this can anyone help me out
Abhijnha
January 25, 2012
error

how can i solve this issue Type mismatch: cannot convert from java.sql.Connection to com.mysql.jdbc.Connection
wassim ahamed
January 25, 2012
doubt

have to install mysql or not
packialakshmi
February 6, 2012
mysql coding

i want more mysql codings using java
virendra verma
February 25, 2012
to connect database

sir,when i write below program,and when i click on submit button,message shows class not found please help me,modify my program import java.sql.*; import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class serve extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); RequestDispatcher rd=request.getRequestDispatcher("index.jsp"); rd.include(request,response); //String name = request.getParameter("username"); //String password = request.getParameter("pass"); String name = request.getParameter("name"); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/demo", "root", "mysql"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("insert into student values('"+name+"');"); while (rs.next()) { out.print("<tr><td>"); out.print(rs.getString(1)); out.print("</td></tr>"); //if(name1 == name) } } catch (Exception e) { out.print(e); } out.flush(); out.print("your name is:"+name); response); } }
om shankar kr
April 7, 2012
database delete

i want do download..............
Hannah
April 11, 2012
thanks!

Fantastic website! Use It all the time when Im looking for some Java help..Thanks alot!
krishna chaithanya
April 17, 2012
chava technology

please upload chava cdbc mysql connection statements pls urgent
Mac
May 13, 2012
java.lang.ClassNotFoundException

Thanks. but i could not run this code. it compiles alright with the credentials for my database but can not run. i get java.lang.ClassNotFoundException Please get back if you can. Thanks again.
adinew
May 22, 2012
to ask a question

I have many I have many comments I have many comments I have many comments I have many comments I have many comments I have many comments comments
anarkali
May 27, 2012
jdbc question

package com.tcs.ilp.Try.Controller; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.tcs.ilp.Try.Model.Beans; import com.tcs.ilp.Try.Model.MyHelper; /** * Servlet implementation class Servlet1 */ public class Servlet1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public Servlet1() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); PrintWriter out=response.getWriter(); out.println("Entred post"); String str2=request.getParameter("submit"); out.println(str2); //ArrayList<Beans> c=new ArrayList<Beans>(); String str=request.getParameter("username"); String str1=request.getParameter("password"); ArrayList<Beans> a=new ArrayList<Beans>(); if(str2.equals("Login")) { System.out.println("Entred if"); //System.out.println(a); int d; d=MyHelper.insert(str,str1); //Beans b=new Beans(); a=MyHelper.view(); session.setAttribute("registration",a); response.sendRedirect("Reg_users.jsp"); } if(str2.equals("Update")) { MyHelper.update(str,str1); } if(str2.equals("logout")) { session.invalidate(); System.out.println("Successfully Deleted"); } } }
Arjoo
June 11, 2012
mysql connection to java

Thanx a lot........it works....
neelu
June 15, 2012
Regarding the code

what is :3306 there in code? Is it same for everybody or if different, how can you find it?
madhu sudan
June 17, 2012
java data base conectivity

there is an exception arrived in my program during execution . 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 Demo.main(Demo.java:11) plz tell me how can i solve this problem............?
suhas
June 25, 2012
java database

I want to know that for java pro which changes have to do for inserting database.i am using sql database?
som
July 16, 2012
moduarising the program

sir may i knw how to make a class and make this program modular..i meaen all the strings should be in properties file.
Joseph
July 21, 2012
error

I get this error when running the file MySQL Connect Example. 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 MysqlConnect.main(MysqlConnect.java:13)
akhil
July 26, 2012
about html

is it possible to connect html pages to mysql?
Pio Baleicoqe
August 2, 2012
Class Not Found Exception

I tried the code above but i got one error message. this message is being throw "java.lang.ClassNotFoundException: com.mysql.jdbc.Driver" I am using JDK 1.6. Is there any problem with my codes. package mysqlconnect; import java.sql.Connection; import java.sql.DriverManager; import javax.swing.JOptionPane; /** * * @author Pio */ public class MysqlConnect { /** * @param args the command line arguments */ public static void main(String[] args) { String n = "MYSQL Database Connection Test!"; JOptionPane.showMessageDialog(null,n,"MYSQL TEST Connection",JOptionPane.INFORMATION_MESSAGE); Connection conn = null; String url = "jdbc:mysql://host167.hostmonster.com:3306/"; String dbName = "xscholar_remington"; String driver = "com.mysql.jdbc.Driver"; String userName = "xscholar_konica"; String password = "return@64Days!"; try { Class.forName(driver).newInstance(); conn = DriverManager.getConnection(url+dbName,userName,password); String cn = "Connected from database!"; JOptionPane.showMessageDialog(null,cn,"Connection Error",JOptionPane.INFORMATION_MESSAGE); System.out.println("Connected to the database"); conn.close(); String cl = "Disconnected from database!"; JOptionPane.showMessageDialog(null,cl,"Connection Error",JOptionPane.INFORMATION_MESSAGE); System.out.println("Disconnected from database"); } catch (Exception e) { String err = "Connection Error -> "+e+"!"; JOptionPane.showMessageDialog(null,err,"Connection Error",JOptionPane.WARNING_MESSAGE); System.out.println("Error - > "+e+"."); } } } Any help will be appreciated.
IGHOT
August 11, 2012
thanks

god bless you rose india !! thanks a lot you're the best.
sowmiya.c
August 18, 2012
i want to jdbc connection program in java

pls reply my email
ace
September 7, 2012
java

which is more easy to use java or php
bhaumik
September 26, 2012
thanks

thank you it is really helpful content
govind
September 30, 2012
sql

kya hum without sql use kiye bina database use nhi kar sakte
prabu
October 25, 2012
MySQL Connection

I downloaded and installed ODBC driver for MySQL in my Windows7 OS.But while adding DSN, the ODBC driver for mySQL is not displaying....Please help....
govind
November 27, 2012
database connectin

it s very useful.
Anand
November 30, 2012
good job..

this site more usefull for beginners..
Balaji
April 1, 2013
Connecting with MySQL

While executing the above program am getting the following error. In my program i removed the UserName and Password and made it as blank. Anybody can suggest Exception in thread "main" java.lang.NoClassDefFoundError: MysqlConnect Caused by: java.lang.ClassNotFoundException: MysqlConnect at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
Er.Raj Roushan
June 12, 2013
connection

What are the procedure to make a connection between java and mysql in control panel.
DMCA.com