JSP- Select Query.
Problem:
Using Select Query, to retrieve the data from table using jsp and mysql.
We follow some steps to connect jsp with mysql database.
1). Load the Driver
Class.forName(“com.mysql.jdbc.Driver”);
This statement load the mysql Driver.
2). Create the Connection
String s=”jdbc:mysql://localhost/Database_Name”,”username”,”password”
Connection con=DriverManager.getConnection(s);
3). Create Statement
Statement stmt=con.createStatement();
String sql=”select * from Table_Name”;
Stmt.executeQuery(sql);
Requirements:
Netbean 6.8
Mysql 6.0
Knowledge from mysql.
Procedure:
Step 1:
Create DataBase named as example.
How to Create Database
Mysql > create database example;
Successfully database is created.
Step 2:
Use database.
How to activate example database?
Mysql > use example;
Step 3:
create table named exam.
Mysql > create table exam(student_name varchar(40),rollno varchar(20));
Step 4:
Insert data into exam table in example database.
Mysql > insert into exam values(‘anbuselvan’,’2k2ccs2006’);
Step 5:
Create jsp file using netbean IDE.
Give any file name for jsp. I have given jsp file name as databaseExam.jsp
Already I have explained How to create jsp file using netbean 6.8. if you forget the procedure. Please remind the previous post and you will continue this post.
Next
Include following coding into databaseExam.jsp
< %@page contentType="text/html" pageEncoding="UTF-8"% >
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
http://www.w3.org/TR/html4/loose.dtd >
< %@page import="java.sql.*" % >
< html >
< head >
< title > Java DataBase Connectivity Example For Select < /title >
< /head >
< body >
< %!
Connection con=null;
ResultSet rs=null;
Statement stmt=null;
% >
< %
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e)
{
out.println(e.getMessage());
}
try
{
con=DriverManager.getConnection("jdbc:mysql://localhost/example","root","sure");
stmt=con.createStatement();
rs=stmt.executeQuery("select * from exam");
while(rs.next())
{
out.println(rs.getString(1));
out.println(rs.getString(2)) ;
}
}
catch(Exception e)
{
out.println(e.getMessage());
}
% >
< /body >
< /html >
You will run the databaseExam.jsp
Step 4:
Note:
Already I have explained how to include mysql-connector.jar in our project.
Run the Application
You will get the output
No comments:
Post a Comment