
How do you connect to the database from JSP?

A Connection to a database can be established from a jsp page by writing the code to establish a connection using a jsp scriptlets.

<%@ page import="java.sql.*" %> <%! String Uname_Text; String Passwd_Text;%> <% Uname_Text=request.getParameter("Uname"); Passwd_Text=request.getParameter("Passwd"); request.setAttribute("Uname",Uname_Text);
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}
catch(Exception e){ out.println("Driver Detection Failed."); }
try{
Connection conn;
Statement stm;
String db = "jdbc:odbc:test";
conn = DriverManager.getConnection(db,"","");
System.out.println("****Connected to database***");
stm = conn.createStatement();
if(Uname_Text=="" || Passwd_Text=="")
{
response.sendRedirect("http://localhost:4040/Myjsp/Login_Fail.jsp");
out.println("Username is empty.");
}
ResultSet rs = stm.executeQuery("select * from Table1 where UnameTable='"+ UnameText +"' AND PasswdTable='"+PasswdText+"'"); while(rs.next()) {
out.println(rs.getInt(1) );
out.println(rs.getString(2) );
out.println(rs.getString(3) );
out.println(rs.getString(4) );
out.println(rs.getString(5) );
out.println(rs.getString(6) );
out.println(rs.getString(7));
out.println();
out.println("");
}
conn.close();
}
catch(SQLException e) {
}
%>

this shows the connection as well as insert command....for update use executeUpdate("upadate command here");
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.