Wednesday, February 9, 2011

Retrieving data in textbox values at run time(onload) from the DataBase(SQL) in JSP page

/*For example You want Retrieve Price of something from database and when the prices in database will be updated then the price in JSP page also will updated,whenever you load the page It will directly connect to database.
In database make a 'table' "price" and make the columns as many u have TEXTBOX and every column would have only 1 row(1 value that u want to fetch) for example there are four different TEXTBOX then You'll only 4 columns .
'price.jsp'
hey guys '<' =< please note that.......
*/

<%
try {

// declare a connection by using Connection interface
Connection connection = null;

/* declare object of Statement interface that is used for executing sql statements. */
Statement statement = null;

// declare a resultset that uses as a table for output data from the table.
ResultSet rs = null;

// Load JBBC driver "com.mysql.jdbc.Driver"
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();


/* Create a connection by using getConnection() method that takes parameters
of string type connection url, user name and password to connect to database.'The database name specified at time of connection could be different from actual databasename' */
connection = DriverManager.getConnection("jdbc:odbc:databasename ","","");

/* createStatement() is used for create statement object that is used for
sending sql statements to the specified database. */
statement = connection.createStatement();

// sql query to retrieve values from the secified table.
String QueryString = "SELECT * from price";
rs = statement.executeQuery(QueryString);

if(rs.next()) {
%>

'<'input type="text" name="price1" value="<%=rs.getString(1)%>" /> <%-- you can disable' disabled="disabled" ' as you want --%>

'<'input type="text" name="price2" value="<%=rs.getString(2)%>"/>
'<'input type="text" name="price3" value="<%=rs.getString(3)%>" />
'<'input type="text" name="price4" value="<%=rs.getString(4)%>"/>

<%----YOU CAN USE IN ' option value ' OF select(dropdownlist) ALSO ---%>


'<'select name="selectRoom" id="selectRoom" onChange="updatesum()" > <%--'updatesum' is method used in calculating amt. --%>

'<'option value="0">Select
'<'option value="<%=rs.getString(1)%>">Price1'<'/option>
'<'option value="<%=rs.getString(2)%>">Price2'<'/option>
'<'option value="<%=rs.getString(3)%>">Price3'<'/option>
'<'option value="<%=rs.getString(4)%>">Price4'<'/option>
'<'/select'>'
<% }

// close all the connections.
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
%>

'<'font size="+3" color="red">
<%
out.println("Unable to connect to database.");
}
%>


/* I hope this will help, any doubts are welcome please....... ask
I hope u guys know how to make connection in JSP */