HOME
Java Server Pages
JSP
Introduction JSP
Syntax JSP Expression
JSP Declaration
JSP Comments
JSP Directives
JSP Actions
JavaBeans
JSP Sessions
JSP JDBC
JSP And HTML Forms
JSP With XML
JSP Exam
|
JSP JDBC
The JDBC (java database connectivity) interface is a pure java API used to access sql statements.
It provides a set of classes and interfaces that ca be used by developers to write applications that can connect to the database at the back end. This interaction can be divided into four steps
-
Open connection to the database
-
Execution an SQL statement
-
Process the result
-
Close the connection to the database
There are several advantages to this approach
The client browser is not required to support java at all
The client can view the page even if there is a firewall imposed
The jsp has full control over how many JDBC connections are made to the server, the client never makes direct JDBC connection to the server.
In this chapter we are using MYSQL and Oracle databases named student which contain a table named students containing name and age
now I will use oracle to insert data into the database
|
<html>
<body bgcolor="lightgreen">
<center>
<form method="post" action="insert.jsp">
<table>
<tr> <td> Name: </td> <td> <input type="text" name="t2" size=20> </td> </tr>
<tr> <td> age<br>(13-Jan-2005): </td> <td> <input type="text" name="t3" size=20>
<tr> <td colspan=2 align=center> <input type="submit" value=" Add " > </td>
</tr>
</table>
</form>
<html>
Connection conn;
Statement stmt;
ResultSet rs;
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection("jdbc:oracle:thin:@sys1:1521:stg","scott","tiger");
stmt = conn.createStatement();
String []val = { request.getParameter("t2"), request.getParameter("t3")};
String sql= "insert into stu value (" + Integer.parseInt(" + val[2] + "'," + val[3] + ")";
out.println(sql);
stmt.executeUpdate(sql);
}
catch(SQLException e)
{
out.println("<br>plz enter valid date" );
}
catch(NumberFormatException ne)
{
out.println("Plz enter in the fields");
}
%>
</body>
</html>
|
now let us see what happened with mysql
<%
String name=request.getParameter("name");
String age=request.getParameter("age");
%>
<%@ page import="java.sql.*" %>
<%
String connectionURL = "jdbc:mysql://freewebs.dot5hostingmysql.com/login?user=username;password=password";
Connection connection = null;
Statement st = connection.createStatement();
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "", "");
PreparedStatement p = connection.prepareStatement("insert into stu VALUES (?,?)");
p.setString(1,"name");
p.setString(2,"age");
p.executeUpdate(); connection.close();
%>
<h1>submitted</h1>
</body></html>
|
|
Inform Friend About This Site |