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

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 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄