我有一张桌子 Table name is PARKTABLE
现在我想在jsp中获取这些值 我的代码在这里
<jsp:useBean id="loginBean" scope="session" class="vustudent.Login" />
<input type="text" name="takei" value='<jsp:getProperty name="loginBean" property="loginid" />' />
<%
String dbId = request.getParameter("takei");
Class.forName("org.apache.derby.jdbc.ClientDriver");
String url= "jdbc:derby://localhost:1527/sample;create=true; user=app; password=app";
Connection con = DriverManager.getConnection(url);
Statement st= con.createStatement();
String query = "SELECT * FROM PARKTABLE WHERE ID =\'"+ dbId + "\' ";
ResultSet rs = st.executeQuery(query);
// iterate through the java resultset
if (rs.next())
{
String placeOne = rs.getString("Place1");
String placeTwo = rs.getString("Place2");
System.out.println("place1" +placeOne);
System.out.println("place1" +placeTwo);
}
%>
</br>
<input type="text" name="pl1value" value='placeOne' />
它在输入文本字段中打印placeOne而不是其值。 我想从数据库中打印placeOne值红色或绿色。 哪里错了?
答案 0 :(得分:2)
需要进行三项更改
String placeOne = null; // declare here
String placeTwo = null;
if (rs.next())
{
placeOne = rs.getString("Place1"); // set value here
placeTwo = rs.getString("Place2");
System.out.println("place1" +placeOne);
System.out.println("place1" +placeTwo);
}
%>
</br>
<input type="text" name="pl1value" value=''<%=placeOne%>' /> // print here
答案 1 :(得分:2)
更改输入文字如下:
<input type="text" name="pl1value" value='<%=placeOne%>' />
然后,更改您的Java
代码,如下所示:
String placeOne = "";
String placeTwo = "";
if (rs.next())
{
placeOne = rs.getString("Place1");
placeTwo = rs.getString("Place2");
System.out.println("place1" +placeOne);
System.out.println("place1" +placeTwo);
}
因此,即使您的查询没有返回任何数据,您的输入类型也可以打印默认值。
答案 2 :(得分:0)
作为Scary Wombat和Ye Win的帖子,它们在逻辑上是正确的。如果我是你,我实际上会使用PreparedStatement
而不是Statement
。我将使用while
语句而不是if
。请参阅下面的代码。
String dbId = request.getParameter("takei");
Class.forName("org.apache.derby.jdbc.ClientDriver");
String url= "jdbc:derby://localhost:1527/sample;create=true; user=app; password=app";
Connection con = DriverManager.getConnection(url);
String query = "SELECT * FROM PARKTABLE WHERE ID = ?";
PreparedStatement st= con.prepareStatement(query);
st.setString(0,dbId);
ResultSet rs = st.executeQuery();
String placeOne = null;
String placeTwo = null;
while (rs.next()) {
String placeOne = rs.getString("Place1");
String placeTwo = rs.getString("Place2");
System.out.println("place1" +placeOne);
System.out.println("place1" +placeTwo);
}
我使用PreparedStatement来防止SQL注入,就像你在Statement上所做的那样,但是当其他程序员看到它时,它更具可读性和清晰性。我一直用ResultSet
检索你的所有结果。