Fanszee 2021-06-11 13:44 采纳率: 100%
浏览 708
已采纳

idea tomcat servlet连接jdbc出错

public class HelloServlet extends HttpServlet {
    private static final long serialVersionUID=1L;
    Connection conn=null;

       public void init(){
        String url="jdbc:mysql://localhost:3306/test?useSSL=true";
        String user="root";
        String pwd="123456";
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn= DriverManager.getConnection(url,user,pwd);
        }catch (ClassNotFoundException e1)
        {
            System.out.println(e1);
            getServletContext().log("驱动程序类找不到!");
        }catch (SQLException e2)
        {
            System.out.println(e2);
        }
}

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ArrayList<product>prolist=null;
        prolist=new ArrayList<product>();
        try
        {
            String sql="SELECT * FROM products";
            PreparedStatement statement=conn.prepareStatement(sql);
            ResultSet result=statement.executeQuery();
            while(result.next())
            {
                product pro=new product();
                pro.setId(result.getInt("id"));
                pro.setPname(result.getString("pname"));
                pro.setBrand(result.getString("brand"));
                pro.setPrice(result.getFloat("price"));
                pro.setStock(result.getInt("stock"));
                prolist.add(pro);
            }
            if(!prolist.isEmpty())
            {
                request.getSession().setAttribute("prolist",prolist);
                response.sendRedirect("/displayAll.jsp");
            }
            else
            {
                response.sendRedirect("/error.jsp");
            }
        }catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

idea  Cannot invoke "java.sql.Connection.prepareStatement(String)" because "this.conn" is null

为什么会出现这个错误呢

  • 写回答

4条回答 默认 最新

  • CSDN专家-sinJack 2021-06-11 15:21
    关注
    问题分析:获取不到连接对象,是因为创建连接对象只在项目运行的时候,创建了。连接对象不是静态对象,所以当你调用的时候,获取到的是空。

    解决:

    方式1、将连接对象定义为静态对象。 static Connection conn=null;

    方式2、每次都调用init()方法,并且该方法返回Connection对象,调用的地方获取返回的对象。

    如有帮助,望采纳。点击我回答右上角【采纳】按钮。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?