Настройка подключения Apache Derby в IntelliJ - PullRequest
0 голосов
/ 18 апреля 2019

Я использую IntelliJ в качестве IDE.Мой учитель уже дал мне немного кода.

У меня есть Java-класс AnimalSurvey (pojo), который создает опрос животных базы данных.

Ниже приведен его конструктор.

    public AnimalSurvey() {


    System.out.println("AnimalSurvey starting in " + framework + " mode.");

    try {
        /*
         * The driver is installed by loading its class. In an embedded
         * environment, this will start up Derby, since it is not already
         * running.
         */
        Class.forName(driver).newInstance();
        System.out.println("Loaded the appropriate driver.");

        props = new Properties();
        props.put("user", "app");
        props.put("password", "app");

        /*
         * The connection specifies create=true to cause the database to be
         * created. To remove the database, remove the directory
         * animalsurvey and its contents. The directory animalsurvey will be
         * created under the directory that the system property
         * derby.system.home points to, or the current directory if
         * derby.system.home is not set.
         */


        String dataPath =System.getProperty("user.home");
        dataPath += "/DerbyDB/";

        conn = DriverManager.getConnection(protocol
            //  + "c:\\cloudscape_db\\animalsurvey;create=true", props); //windows
        + dataPath+"animalsurvey;create=false", props);                  //Macos


        System.out
                .println("Connected to and created database animalsurvey");

        conn.setAutoCommit(false);

    } catch (Throwable e) {
        System.out.println("exception thrown:");

        if (e instanceof SQLException) {
            printSQLError((SQLException) e);
        } else {
            e.printStackTrace();
        }
    }

ИМетод initialize () в этом классе AnimalSurvey:

public void initialize()throws SQLException{

    /*
     * Creating a statement lets us issue commands against the
     * connection.
     */
    s = conn.createStatement();

    s.execute("drop table surveyresults");


    /*
     * We create a table, add a few rows, and update one.
     */
    s.execute("create table surveyresults (id int NOT NULL , surveyoption varchar (20) NOT NULL , votes int NOT NULL , constraint surveyresults_id primary key (id)) ");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (1, 'Dog', 0)");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (2, 'Cat', 0)");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (3, 'Bird', 0)");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (4, 'Snake', 0)");
    s.execute("insert into surveyresults (id,surveyoption,votes) values (5, 'None', 0)");
    /*
     * We select the rows and verify the results.
     */
    rs = s.executeQuery("SELECT * FROM surveyresults ORDER BY surveyoption");
    rmd = rs.getMetaData();
}

Теперь у меня есть Java-сервлет, который содержит следующий код, объект AnimalSurvey инициализируется, а затем определяется метод initialize () для этого объекта:

    AnimalSurvey dataObject = new AnimalSurvey();
    dataObject.initialize();

Когда я запускаю свою веб-программу и попадаю в этот Java-сервлет, я всегда получаю HTTP Status 500?Внутренняя ошибка сервера, и это дает мне следующее исключение:

java.lang.NullPointerException
data.AnimalSurvey.initialize(AnimalSurvey.java:184)
be.SurveyServlet.doPost(SurveyServlet.java:25)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

Таким образом, в классе AnimalSurvey, в методе initialize, выглядит следующий код (в этом классе было установлено значение private Connection conn null),все еще нулевое, когда я выполняю код.

s = conn.createStatement();

Код много, я знаю, и надеюсь, что это имеет смысл.Мой учитель также дал мне следующую информацию, чтобы иметь доступ к базе данных: 'jdbc: derby: // localhost: 1527 / surveyresults; пользователь = приложение; пароль = приложение;

Но как мне получить ApacheДерби работает?Нужно ли скачивать драйверы?И где в IntelliJ мне установить соединение с этой базой данных?

...