This example is showing how to create class file and how to use that class file in jsp page.
here I am showing example without using eclipse or any IDE.
When we are developing any project, we need to create one separate class file for connecting with database so here I am creating one class file which is java class file and I will use whenever i need to connect with database.
First you need to create class.
DatabaseConnection.java
package myCon;
import java.sql.*;
public class DatabaseConnection
{
private static Connection connection;
static
{
try
{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost/cosociety", "root", "");
} catch (Exception e)
{
System.out.println(e.toString());
}
}
public static Connection getConnection()
{
return connection;
}
}
The above java file which i created is to get connection with the database.
When you are creating class, you have to create package for that.If you are not creating package, then at run time jvm always search class file in default package and the class file will not found so jvm will throw errors.so for that we need to create package and our class file we need to store in package.
Now for compilation:
This following compilation is doing using the cmd.
C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\slvsc\inc>javac -
d . DatabaseConnection.java
after executing the above command, your class file will be available inside the package, "myConn".
Now you have to create structure for your project.
You have to put myConn package inside the
WEB-INF->classes
you have to create folder like above and put your package inside classes folder.
Now structure is
WEB-INF->classes-> myCon->DatabaseConnection.class
Then you can call it using the following way.
The following example is used for retrieving data from employee table.
<%@ page import="myCon.DatabaseConnection"%> //this line used for import class in jsp page
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*" %>
<%!
Connection connection;
String sql="";
Statement stmt;
ResultSet rs,rsn;
%>
<%
try
{
connection=DatabaseConnection.getConnection();
stmt=connection.createStatement();
sql="select *from employee";
rs=stmt.executeQuery(sql);
while(rs.next())
{
out.println(rs.getString("EMP_Name"));
}
}
catch(SQLException sa)
{
out.println("Error loading driver:" + sa.getMessage());
}
%>
No comments:
Post a Comment