0

Hello I am creating a web page to add some information about given product.I need to enter id,name,description and image as information.I need the id to be auto generated.I am using jsp and database as access.I am fetching the count(*)+1 value from database and assigning to my html text box but its showing as null.can i get some help?

Code:

<body>
<%@page import="java.sql.*"%>
<%! String no; %>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:pd");
ResultSet rs = null;
Statement st = con.createStatement();
String sql = ("select count(*)+1 from products");
st.executeUpdate(sql);
while (rs.next()) { 
no=rs.getString("count(*)+1");
}
rs.close();
st.close();
con.close();
}
catch(Exception e){}
%> 
<Form name='Form1' action="productcode.jsp" method="post">
<table width="1024" border="0">
  <tr>
    <td width="10">&nbsp;</td>
    <td width="126">Add Product: </td>
    <td width="277">&nbsp;</td>
    <td width="583">&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>Product Id:</td>
    <td><label>
      <input type="text" name="id" value="<%= no%>"/>
    </label></td>
    <td>&nbsp;</td> 
.... and so on
prakash_d22
  • 1,153
  • 5
  • 21
  • 34

2 Answers2

2
  {..}.executeQuery("Select max(id) from tablename");

This will return the ID with the largest number. Its more efficient than select * from tablename order by id desc limit 1.

However, it looks like your trying to guess/generate an ID of an object which doesn't yet exist in the database. This isn't the best way, and you may find that the ID your generating may be different to that generated by your DB. It could also cause duplication errors if two people are trying to create two new objects at the same time.

I would suggest that you don't provide a product id until the "create product" button has been pressed. Use @@IDENTITY; in your SQL command to set the new ID to your product safely.

JDandChips
  • 9,780
  • 3
  • 30
  • 46
1

You wrote a query to get the data like this

          String sql = ("select count(*)+1 from products");
          st.executeUpdate(sql);

The statement

            executeUpdate()

only used to do the operations like INSERT,UPDATE

try

             rs=st.executeQuery(sql); 

instead of executeUpdate()

Aravindhan
  • 3,566
  • 7
  • 26
  • 42