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".
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.

|
Current Comments
16 comments so far (post your own) View All Comments Latest 10 Comments:java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at ava.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.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at MysqlConnect.main(MysqlConnect.java:13)
Posted by mohan on Friday, 02.22.08 @ 11:11am | #49387
Hi ,
i have tried for this program, and it is succefully compiled and giving some exception error while running this program.So what i have to do for this .
Posted by venkat on Wednesday, 01.30.08 @ 11:13am | #46569
hello,
I have tried this program. But I got an error like,
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at ava.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.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at MysqlConnect.main(MysqlConnect.java:13)
can anybody help to run this program.
Posted by subbulakshmiGanesan on Friday, 12.28.07 @ 10:53am | #44016
Hi
I have set the class path as
CLASSPATH = D:\tomcat\common\lib\mysql-connector-java-5.1.5-bin.jar
Posted by sreenivasa y on Thursday, 12.27.07 @ 14:29pm | #43943
this has been sent by ansar khan
Posted by ansar on Friday, 12.14.07 @ 22:33pm | #42307
---------- run ----------
java.lang.ClassNotFoundException: org.gjt.mm.mysql.Driver
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:290)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:279)
at java.lang.ClassLoader.loadClass(ClassLoader.java:236)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:303)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:164)
at connection.main(connection.java:9)
Output completed (0 sec consumed) - Normal Termination
Posted by Dileep on Monday, 10.8.07 @ 11:40am | #32447
Hi,
Iam unable to do the compilation of aservlet page. im getting so many errors on servlet package.like import javax.servlet.http.*;
Posted by shiva on Sunday, 08.19.07 @ 12:05pm | #23719
HTTP Status 500 -
--------------------------------------------------------------------------------
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: Unable to compile class for JSP
An error occurred at line: 10 in the jsp file: /project/validate.jsp
Generated servlet error:
[javac] Compiling 1 source file
C:\Tomcat 4.1\work\Standalone\localhost\_\project\validate_jsp.java:61: cannot resolve symbol
symbol : variable staff
location: class org.apache.jsp.validate_jsp
rs=st.executeQuery("select * from login where username='"+staff+"'");
^
An error occurred at line: 10 in the jsp file: /project/validate.jsp
Generated servlet error:
Note: C:\Tomcat 4.1\work\Standalone\localhost\_\project\validate_jsp.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
1 error
at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:130)
at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:293)
at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:340)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:352)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:474)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:184)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
at java.lang.Thread.run(Thread.java:484)
--------------------------------------------------------------------------------
Apache Tomcat/4.1.18
Posted by pattabhi on Saturday, 08.18.07 @ 14:13pm | #23649
hv tried the above example.i got the following error.
MySQL Connect Example.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at ava.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.ClassLoader.loadClassInternal(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at MysqlConnect.main(MysqlConnect.java:13)
can anyone help me to check out this problem
Posted by Maniraj on Friday, 07.27.07 @ 11:21am | #22033
i had the same problem and it got resolved after setting the classpath for mysql's jar.
Posted by raja on Sunday, 06.10.07 @ 22:34pm | #18828