该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
我自己试了一下直接查询id为1的语句,有一条结果出来,但是用了PreparedStatement后就没有结果了,有大佬知道为什么吗orz
package test;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import atg.taglib.json.util.JSONArray;
import atg.taglib.json.util.JSONObject;
@WebServlet("/Proinfo")
public class Proinfo extends HttpServlet {
private static final long serialVersionUID = 1L;
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC";
static final String USER = "root";
static final String PASS = "root";
/**
* @see HttpServlet#HttpServlet()
*/
public Proinfo() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
Statement stmt = null;
int id=1;
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM all_products where productid=?";
stmt=conn.prepareStatement(sql);
((PreparedStatement) stmt).setInt(1,id);
ResultSet rs = stmt.executeQuery(sql);
JSONArray array=new JSONArray();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
while (rs.next()) {
JSONObject jsonObj = new JSONObject();
for (int i = 1; i <= columnCount; i++) {
String columnName =metaData.getColumnLabel(i);
String value = rs.getString(columnName);
jsonObj.put(columnName, value);
}
array.put(jsonObj);
}
out.println(array);
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}