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
为什么会出现这个错误呢
问题分析:获取不到连接对象,是因为创建连接对象只在项目运行的时候,创建了。连接对象不是静态对象,所以当你调用的时候,获取到的是空。
解决:
方式1、将连接对象定义为静态对象。 static Connection conn=null;
方式2、每次都调用init()方法,并且该方法返回Connection对象,调用的地方获取返回的对象。
如有帮助,望采纳。点击我回答右上角【采纳】按钮。
conn 为null,数据库没有连接上,先用main方法测试数据库连上后再做操作
检查账号密码还有驱动是否正确!
调用init()了吗 ,创建
Connection 了吗
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632