0

您好,我正在创建一个网页以添加有关给定产品的一些信息。我需要输入 id、名称、描述和图像作为信息。我需要自动生成 id。我使用 jsp 和数据库作为访问。我正在获取数据库中的 count(*)+1 值并分配给我的 html 文本框,但它显示为 null。我能得到一些帮助吗?

代码:

<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
4

2 回答 2

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

这将返回ID具有最大数字的。它比select * from tablename order by id desc limit 1.

但是,看起来您试图猜测/生成ID数据库中尚不存在的对象。这不是最好的方法,您可能会发现ID您的生成可能与您的数据库生成的不同。如果两个人同时尝试创建两个新对象,也可能导致重复错误。

我建议您在按下“创建产品”按钮之前不要提供产品 ID。@@IDENTITY;在您的 SQL 命令中使用以ID安全地为您的产品设置新的。

于 2012-09-15T09:36:09.313 回答
1

你写了一个查询来获取这样的数据

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

该声明

            executeUpdate()

仅用于执行 INSERT、UPDATE 等操作

尝试

             rs=st.executeQuery(sql); 

而不是 executeUpdate()

于 2012-09-15T09:22:03.920 回答