从servlet连接时接收连接对象

时间:2013-09-04 08:50:23

标签: java servlets jdbc nullpointerexception connection

从servlet实例化它时我怎么都不能接收连接对象,但我可以从标准的Java应用程序(使用相同的代码)完成它, 这是我的代码后跟异常

    try {
    Statement st = null;
    Connection con = null;
    try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/bd?user=root&password=pass");
            st = con.createStatement();
            System.out.println("SELECT * FROM user WHERE 'userName'="+c(userName));
                st.execute("INSERT INTO user ('userName', 'password', 'email') VALUES ('FEF','RR','GG')");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

java.lang.NullPointerException
at Authentificate.testBD(Authentificate.java:52)
at Authentificate.doGet(Authentificate.java:36)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)

2 个答案:

答案 0 :(得分:1)

似乎没有初始化Statement对象,这就是你得到异常的原因。

st.execute(sql);之前尝试:

st = con.createStatement();

答案 1 :(得分:0)

你应该尝试st.executeUpate而不是st.execute。