Connect JSP With Mysql
Connect JSP With Mysql
Connect JSP With Mysql
In this example we will show you how to connect to MySQL database from your JSP
code. First, you need to create database and then write jsp code to connect jsp to
database.
1. Create a database:
First create a database named usermaster in mysql. Before running the jsp code you
need to paste mySqlConnector.jar in lib directory of jdk.
ConnectJspToMysql.jsp
<html>
<head>
<title>Connection with mysql database</title>
</head>
<body>
<h1>Connection status </h1>
<%
try {
/* Create string of connection url within specified format
with machine name,
port number and database name. Here machine name id
localhost and
database name is usermaster. */
String connectionURL =
"jdbc:mysql://localhost:3306/usermaster";
// declare a connection by using Connection interface
Connection connection = null;
Output:
Output of the program when connection is established with specified mysql database :
Output of the program when unable to connect to specified MySQL database :
This is detailed jsp code that shows how to navigate in database. This code shows one
by one record of student from database on clicking a button labeled 'next record', so
on each click of button application fetches next record from database, this is the
navigation in database.
Create a database: Before run this jsp code first create a database named 'student'
through the sql query given below in mysql command prompt :-
mysql> create
database student;
Then create a table named 'stu_info' in the same database through following sql
query :-
ConnectJspToMysql.jsp
Class.forName("com.mysql.jdbc.Driver").newInst
ance();
/* Create a connection by
using getConnection()
method that takes parameters
of string type connection
url, user name and password to
connect to database. */
connection =
DriverManager.getConnection(connectionURL,
"root", "root");
/* createStatement() is used
for create statement
object that is used for
sending sql statements to
the specified database. */
statement =
connection.createStatement();
// executeQuery() method
execute specified sql query.
rs =
statement.executeQuery("select * from
stu_info");
for (int i = 0; i < current;
i++) {
rs.next();
}
if (!rs.next()) {
%>
<FONT size="+2" color="red"></b>
<%
out.println("Sorry ! found some
problems with database.");
} else {
%>
<TABLE style="background-color: #ECE5B6;"
WIDTH="30%" >
<TR><TH width="50%">ID</TH><TD
width="50%"> <%= rs.getInt(1)%>
</TD></tr>
<TR><TH>Name</TH><TD> <%=
rs.getString(2)%> </TD></tr>
<TR><TH>City</TH><TD> <%=
rs.getString(3)%> </TD></tr>
<TR><TH>Phone</TH><TD> <%= rs.getInt(4)%>
</TD></tr>
</TR>
</TABLE>
<BR>
<INPUT TYPE="hidden" NAME="hidden" VALUE="<
%=current + 1%>">
<INPUT TYPE="submit" VALUE="next record">
</FORM>
<%
}
}
catch (Exception ex) {
%>
<FONT size="+3" color="red"></b>
<%
out.println("Unable to connect
to database.");
} finally {
// close all the connections.
rs.close();
statement.close();
connection.close();
}
%>
</FONT>
</FORM>
</body>
</html>
This example shows how to update the existing record of mysql table using jdbc
connectivity in the jsp page. In this example we have created two jsp pages
update.jsp and updatingDatabase.jsp. In the update.jsp page, we are using a Text
box where user can give his/her name and submit the page. After submitting the
page, updatingDatabase.jsp will be called and the sql query ("update servlet set
name = ? where id = ?") is executed which will modify the table record.
<%@page language="java" session="true"
contentType="text/html;charset=ISO-8859-1" %>
<font color="blue">Please Enter Your Name </font><br><br>
<form name="frm" method="post" action="updatingDatabase.jsp">
<table border = "0">
<tr align="left" valign="top">
<td>Name:</td>
<td><input type="text" name ="name" /></td>
</tr>
<tr align="left" valign="top">
<td></td>
<td><input type="submit" name="submit" value="submit"/></td>
</tr>
</table>
</form>
updatingDatabase.jsp
<%@ page language = "java" contentType =
"text/html; charset = ISO-8859-1"
import = "java.io.*"
import = "java.sql.*"
import = "java.util.*"
import = "javax.sql.*"
import = "java.sql.ResultSet"
import = "java.sql.Statement"
import = "java.sql.Connection"
import = "java.sql.DriverManager"
import = "java.sql.SQLException"
%>
<%
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
Statement stmt = null;
String name = request.getParameter("name");
Integer id = 5;
%>
<html>
<head>
<title>Updating Database</title>
</head>
<body>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("jdbc:mysql://192.168.10.59:3306/example",
"root", "root");
ps = con.prepareStatement("update servlet set
name = ? where id = ?");
ps.setInt(2, id);
ps.setString(1, name);
ps.executeUpdate();
%>
Database successfully Updated!<br>
<%
if(ps.executeUpdate()>=1){
stmt=con.createStatement();
rs = stmt.executeQuery("SELECT * FROM servlet");
while(rs.next()){
%>
<%=rs.getObject(1).toString()%>
<%=("\t\t\t")%>
<%=rs.getObject(2).toString()%>
<%=("<br>")%>
<%
}
}
} catch (IOException e) {
throw new IOException("Can not display records.", e);
} catch (ClassNotFoundException e) {
throw new SQLException("JDBC Driver not found.", e);
} finally {
try {
if(stmt != null){
stmt.close();
stmt = null;
}
if(ps != null) {
ps.close();
ps = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
%>
</body>
</html>
After submitting the name, it will be updated in the database and the records will be
displayed on your browser.
This is detailed jsp code that shows how to create dynamic page. This code shows one
by one record of student from database on click a button named 'next record'. On
each click of button, application fetch next record from database.
Create a database : Before running this jsp code, first create a database named
'student' through the sql query given below in mysql command prompt :-
Then create a table named 'stu_info' in the same database through following sql query
:-
ConnectJspToMysql.jsp:
This file provides full code how to connect with database and showing the next record
of database in JSP.
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using
getConnection() method that takes
parameters of string type connection
url, user name and password to
connect to database. */
connection =
DriverManager.getConnection(connectionURL, "root",
"root");
/* createStatement() is used for
create statement object that is
used for sending sql statements to the
specified database. */
statement =
connection.createStatement();
// executeQuery() method execute
specified sql query.
rs = statement.executeQuery("select *
from stu_info");
for (int i = 0; i < current; i++) {
rs.next();
}
if (!rs.next()) {
%>
<FONT size="+2" color="red"></b>
<%
out.println("Sorry ! found some problems with
database.");
} else {
%>
<TABLE style="background-color: #ECE5B6;" WIDTH="30%"
>
When click on button, application control goes to database and check for the next
record. If next record is found in table, it is shown in browser else an error message.
Error message page:
This is first jsp page that has a link 'show data from table', which displays all the
data from table when clicked. This is the code of first welcome jsp page.
welcome_to_database_query.jsp
<html>
<head>
<title>display data from the table
using jsp</title>
</head>
<body>
<TABLE style="background-color:
#ffffcc;">
<TR>
<TD align="center">
<h2>To display all the data from the table
click here...</h2></TD>
</TR>
<TR>
<TD align="center"><A
HREF="ConnectJspToMysql.jsp">
<font size="4"
color="blue">show data from
table</font></A></TD>
</TR>
</TABLE>
</body>
</html>
ConnectJspToMysql.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.d
td">
<html>
<head>
<title>display data from the
table using jsp</title>
</head>
<body>
<h2>Data from the table 'stu_info'
of database 'student'</h2>
<%
try {
/* Create string of
connection url within specified
format with machine name,
port number and database name.
Here machine name id
localhost and database name is
student. */
String connectionURL =
"jdbc:mysql://localhost:3306/studen
t";
// declare a connection
by using Connection interface
Connection connection =
null;
// declare object of
Statement interface that is used
for
executing sql statements.
Statement statement =
null;
// declare a resultset
that uses as a table for output
data
from tha table.
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Drive
r").newInstance();
/* Create a connection by
using getConnection()
method that takes
parameters of string type
connection url, user name
and password to connect to
database. */
connection =
DriverManager.getConnection(connect
ionURL, "root", "root");
/* createStatement() is
used for create statement
object that is used for sending sql
statements to the specified
database. */
statement =
connection.createStatement();