Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > После доступа к базе выпадает javaNullPointerExcep


Автор: Dzo 10.6.2008, 13:05
Код



import java.sql.*;

public class Database {

    public Connection connection;

    // for a while user and pass here
    public static final String USER = "1234";
    public static final String PWD = "1234";
    
    public Connection dbConnect(String user, String pwd) {
        
        // create connection
        
        try {
            
            Class.forName("com.mysql.jdbc.Driver"); // register jdbc
            // create connection
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/blabla?" + "user="+user+"&password="+pwd);
        
        } catch (SQLException e) {
            
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
            
        } catch (ClassNotFoundException ex) {
            
            System.out.println("JDBC registration error: " + ex.getMessage());
        } 
        
        return connection;
        
    }
    
    public void dbClose() {
        try {
            connection.close();
        } catch (SQLException e) {
            
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        }
    }
    
    public static void main (String args[]) {
        Database db = new Database();
        Connection connection = db.dbConnect("1234", "1234");
        
        String todo = ("INSERT INTO menuelements VALUES(1,test,test,test,1,1,1)");
        try {
        Statement s = connection.createStatement();
        s.executeUpdate(todo);
        } catch (SQLException e) {
            
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        }
        
    }
}



Ошибка такая:

Exception in thread "main" java.lang.NullPointerException
    at ee.ebsa.core.Database.main(Database.java:56)


56 строка:
Statement s = connection.createStatement();

Я искал в нете решение, но глухо.

HELP!

Автор: Shurr 10.6.2008, 13:16
Dzo
В методе dbConnect новый коннекшн присваивается локальной переменной connection, а возвращается поле объекта Database, которое тоже называется connection.

Автор: AntonSaburov 10.6.2008, 13:16
Ты внутри try ... catch создал ЛОКАЛЬНУЮ переменную connection, а возвращаешь член класса, который пока не инциализирован, т.е. = null.

Автор: ivg 10.6.2008, 13:16
Код

19:              connection = DriverManager.getConnection("jdbc:mysql://localhost/blabla?" + "user="+user+"&password="+pwd);


Добавлено через 37 секунд
 smile 

Автор: Dzo 10.6.2008, 13:31
ДУРАК!  smile 

Спасибо!

Автор: AntonSaburov 10.6.2008, 13:45
Да уж - три человека почти одновременно отвечают. Показательно - народа на форуме немало. Что не может не радовать smile

Автор: Dzo 10.6.2008, 13:56
: ( Я чего-то вообще туплю.

Суть такая:

Я захотел вынести всю хрень для соеденения с базой в отдельный класс.

Код

import java.sql.*;

public class Database {

    public Connection connection;

    // for a while user and pass here
    public static final String USER = "1234";
    public static final String PWD = "1234";
    
    public Connection dbConnect(String user, String pwd) {
        
        try {
            
            Class.forName("com.mysql.jdbc.Driver"); // register jdbc
            // create connection
            connection = DriverManager.getConnection("jdbc:mysql://localhost/blabla?" + "user="+user+"&password="+pwd);
        
        } catch (SQLException e) {
            
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
            
        } catch (ClassNotFoundException ex) {
            
            System.out.println("JDBC registration error: " + ex.getMessage());
        } 
        
        return connection;
    }
    
    public void dbClose() {
        try {
            connection.close();
        } catch (SQLException e) {
            
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        }
    }
}


Теперь у меня есть сервлет, задача которого, дико простая - добавлять инфу в базу.

Код


import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ee.ebsa.core.Database;

import java.sql.*;

public class MenuElements extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   
    public MenuElements() {
        super();
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String elmName = request.getParameter("elmName");
        String titleEst = request.getParameter("titleEst");
        String titleEng = request.getParameter("titleEng");
        String pageID = request.getParameter("pageID");
        String parentID = request.getParameter("parentID");
        String position = request.getParameter("position");
        
        // adding info to database
        try {
            Database db = new Database();
            Connection dbConnection = db.dbConnect(db.USER,db.PWD);
            
            String sqlTemp = "INSERT INTO menuelements VALUES(1,?,?,?,?,?,?)";
            PreparedStatement sqlQuery = dbConnection.prepareStatement(sqlTemp);
             
            sqlQuery.setString(2,elmName);
            sqlQuery.setString(3,titleEst);
            sqlQuery.setString(4,titleEng);
            sqlQuery.setString(5,pageID);
            sqlQuery.setString(6,parentID);
            sqlQuery.setString(7,position);
            
            int r = sqlQuery.executeUpdate();
            sqlQuery.close();
            dbConnection.close();
        
        } catch (SQLException e) {
            System.out.println("SQLException: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("VendorError: " + e.getErrorCode());
        }
        
    }
}



Когда я его запускаю, мне опять валицца ошибка nullPointerException : ((

java.lang.NullPointerException
    MenuElements.doPost(MenuElements.java:36)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

Это то что томкат говорит, а в консоле еще мелькает JDBC registration error: com.mysql.jdbc.Driver

Правильно ли я понимаю, что из-за того, что вылазит ошибка с регистрацией коннектора, получается значение нулл для моего коннекта к базе в сервлете. Просто, если отдельно тестировать класс Database все работает!

Автор: Dzo 10.6.2008, 14:16
 smile 

Автор: Dzo 10.6.2008, 15:01
Проблема решена.

Забыл добавить в папочку lib коннектор джар : )

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)