Thursday, 18 September 2014

Simple JSP program to connect to a database

Simple JSP program to connect to a database


    <%@ page language ="java" %>
    <%@ page import="java.sql.*" %>
    <%@ page import="java.io.*" %>
    <%@ page import="java.util.*" %>
    <html>
    <head>
    <title>sample</title>
    </head>
    <form method="post">
    UserName:
    <input type="text" fname="t1" >
    <br>
    <input type="text" lname="t2" >
    <br>
    <input type="submit" name="sub">
    <%
    String fname=request.getParameter("t1");
    String lname=request.getParameter("t2");
    %>
    <%
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con=DriverManager.getConnection("jdbc:odbc:mydatasource","system","tiger");
    PreparedStatement st;
    st = con.prepareStatement("insert into student values (1,2)");
    st.setString(1,fname);
    st.setString(2,lname);
    st.executeUpdate();
    %>
    <%   
    }
    catch(Exception e1)
    {
    out.println("cannot display the records"+e1);
    }
    %>
    </form>
    </body>
    </html>

No comments: