Wednesday, August 27, 2014

How To Connect Jsp And Mysql Using Eclipse

This tutorial will teach you how to connect mysql database and jsp on eclipse. I really had a hard time connecting jsp and mysql since i could not find any right resource on internet. So i thought i would share my experience. Here am using eclipse indigo.

Getting started:

Prerequisites: 
  1. Apache Tomcat web server
  2. Mysql Server. (If you install wamp server you can manage sql through phpmyadmin, so that you dont have to mess around with mysql command line tool)
Step1: Create a dynamic web project by going to File-->New-->Dynamic web project.


Step2: Give your project a name and select the target run-time as Apache tomcat, that you have installed in you system already, and click finish.Now you workspace is ready for the sql connection test.



Step3: Create a new file called ConnectJspToMysql.jsp and paste the following code.
<% 
try {
/*here mysqltest is the database name. you have to give the database name you have created and 3306 is the default sql port */
String connectionURL = "jdbc:mysql://localhost:3306/mysqltest"; 

Connection connection = null; 

Class.forName("com.mysql.jdbc.Driver").newInstance(); 

/* "root" and "root" are the mysql username and password . if you have a different user name and password you have to change that in code */

connection = DriverManager.getConnection(connectionURL, "root", "root");

if(!connection.isClosed())
%>
<% 
out.println("Successfully connected to " + "MySQL server using TCP/IP...");
connection.close();
}
catch(Exception ex){
%>
<%
out.println("Unable to connect to database.");
}
%>
Step4: Download MySql connector and add it to eclipse. Dowload it here. Now unzip the dowloaded file in some location.

Step 5: Now got to eclipse. Expand your project folder . Go to java resources-->Libraries-->Ear libraries and then right click on EAR libraries. You will see an option calledconfigure build path. select that option and select "add external jar files"  and find the uzipped mysl connector folder and select the 
java-mysql-connector.jar file and click open. 


That it, Now you can run your jsp program and you will get an output saying , connection established using tcp ip.

No comments:

Post a Comment