java使用ifelse语句修改jstl中的代码

zc0qhyus  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(340)
<% 
  try
  {
  Class.forName("com.mysql.jdbc.Driver").newInstance();;
  Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/newschema", "root", "root");
  Statement st = con.createStatement();
  String userid=request.getParameter("userid");
  String name=request.getParameter("name");
  String shift=request.getParameter("shift");
  String role=request.getParameter("role");
  String strQuery = "SELECT COUNT(*) FROM employee WHERE emp_id='"+userid+"'";
  ResultSet rs = st.executeQuery(strQuery);
  rs.next();
  String Countrow = rs.getString(1);
  out.println(Countrow);
  if(Countrow.equals("0"))
  {
   int i=st.executeUpdate("INSERT INTO employee(emp_id,name,shift)VALUES('"+userid+"','"+name+"','"+shift+"')");
   out.println("Data is successfully inserted!");
  }
  else
  {
   out.println("Employee data already exists !");
  }
 }
 catch(Exception e)
 {
  System.out.print(e);
  e.printStackTrace();
 }
 %>

我试图将此代码更改为jstl,并尝试使用语法创建if else语句。但是我不知道如何在if语句下执行sql语句。没有下面的if语句。

<body>
    <c:if test="${ empty param.userid or empty param.name or empty param.shift}">
        <c:redirect url="insert.jsp" >
            <c:param name="errMsg" value="Please Enter the Details" />
        </c:redirect>
     </c:if>

    <sql:setDataSource var="dbsource" driver="com.mysql.jdbc.Driver"
                       url="jdbc:mysql://localhost/newschema"
                       user="root"  password="root"/>

        //<c:if ....>--?

            <sql:update dataSource="${dbsource}" var="result">
            INSERT INTO employee(emp_id, name, shift) VALUES (?,?,?);
            <sql:param value="${param.userid}" />
            <sql:param value="${param.name}" />
            <sql:param value="${param.shift}" />
        </sql:update>

  <c:when test="${result>=1}">
            <font size="5" color='green'> Data inserted successfully.</font>
            <c:redirect url="insert.jsp" >
                <c:param name="susMsg" value="Data inserted successfully." />
            </c:redirect>

         //<c:otherwise ....>---?

</body>

我几乎做到了如上所示。但我有点困在代码检查重复条目从数据库。感谢您的帮助。提前谢谢

snvhrwxg

snvhrwxg1#

请看本页底部的示例。我没有地方测试这个,但我相信它至少能让你靠近。

<sql:query dataSource="${dbsource}" var="result">
    SELECT COUNT(*) as row_count FROM employee WHERE emp_id = ?;
    <sql:param value="${param.userid}" />
</sql:query>

<c:choose>
    <c:when test="${result.rows[0].row_count == 0}">
        <sql:update>...</sql:update>
    </c:when>
    <c:otherwise>
        Employee data already exists!
    </c:otherwise>
</c:choose>

相关问题