java 预处理语句_预处理语句PreparedStatement到底咋用啊

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

我自己试了一下直接查询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);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值