JSP Java Code to Post Data to SQL database using Tomcat Server

JSP is widely used Java based server side scripting language . Here in this tutorial I am going to give you code which  will post data from a html form. before you run through code ensure that the tomcat server is installed or you can download it directly from the official website also download and install Microsoft server 2000.Go to the database console and

1.Create  database named "student1".

2.Create table with four fields NAME,ID,AGE and BRANCH , keep ID as primary key.

First we began with creating a html form. For consideration here we are going to create a form for entering student details such as NAME,ID,AGE and BRANCH. The following is the code for form . Just name it addstud.jsp . After submit button is pressed  then the details are forwarded to addstudinfo.jsp which connects to the database and enters the data into mysql database.

addstud.jsp

<%@page session="true"import="java.io.*"%>
<html>
<body bgcolor="#d0d0d0">
<br></br>
<br></br>
<br></br>
<h2><center>enter stuent details</center></h2>
<form name="addstud"action="addstudinfo.jsp"method="post">
<table border="2"align=center>
<tr><td>
<b>student name:</b>
<input type="text"name="name"/>
<br/>
<br/>
</td></tr>
<tr><td>
<b>id:</b>
<input type="text"name="id"/>
<br/>
<br/>
</td></tr>
<tr><td>
<b>age:</b>
<input type="text"name="age"/>
<br/>
<br/>
</td></tr>
<tr><td>
<b>branch:</b>
<input type="text"name="branch"/>
<br/>
<br/>
</td></tr>
</table>
<center>
<input type="submit"value="submit"/>
<input type="reset"value="reset"/>
<input type="button"value="delete"/>
</form>
</body>
</html>

addstudinfo.jsp

<%@page session="true"import="java.io.*"%>
<html>
<body bgcolor="#d0d0d0">
<br></br>
<br></br>
<%@page import="java.sql.*"%> //imports 
<%@page import="java.util.*"%>
<%
Connection con=null; 
Statement stmt=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:student1","username","password");
try
{
String s1=request.getParameter("name");
String s2=request.getParameter("id");
String s3=request.getParameter("age");
String s4=request.getParameter("branch");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:student1","sa","sa");
stmt=con.createStatement(); //opening a connection
stmt.executeUpdate("insert into studentinfo(name1,id1,age,branch)values('"+s1+"','"+s2+"','"+s3+"','"+s4+"')");
%>
//inserting into database

data enterd successfully...........
<%
stmt.close();//close conncetion
stmt=null;
}
finally
{
if(con!=null)
{
con.close();
}
}
%>
</body>
</html>




Keep both the files in the tomcat server and then run it from the browser on port 8000 (or as configured on the system)
.

0 comments:

Post a Comment

If You Are Asking Some Question On This Comment Then Click On Subscribe by email Link