简体   繁体   English

Java:我在从另一个类连接到数据库时遇到问题

[英]Java: I'm having an issue connecting to a database from another class

I'm making a simple address book app. 我正在制作一个简单的通讯录应用程序。 I have a DatabaseUtility class, which has one method, connectToDatabase() is responsible for pulling info from an embedded database (Java DB) and constructing Contact objects from it. 我有一个DatabaseUtility类,该类具有一种方法,connectToDatabase()负责从嵌入式数据库(Java DB)中提取信息并从中构造Contact对象。

These Contact objects are then placed into an ArrayList and then the entire ArrayList is returned. 然后将这些Contact对象放入ArrayList中,然后返回整个ArrayList。 Yes, I know this is poor programming. 是的,我知道这是糟糕的编程。 It makes more logical sense to have separate methods for connecting and constructing objects, but this is kind of a quick little project I'm doing for practice, and I think I can get by, right? 使用单独的方法来连接和构造对象更合乎逻辑,但这只是我正在练习的一个小项目,我想我可以接受,对吧?

Anyways, I also have a ContactControl class which contains an instance of the DatabaseUtility class as one of it's fields, as well as a private ArrayList of Contacts as one of it's fields. 无论如何,我还有一个ContactControl类,其中包含DatabaseUtility类的一个实例作为其字段之一,以及一个私有的ArrayArray of Contacts作为其字段之一。

What I want is for the ArrayList in the ContactControl class to be instantiated by the return value of the connectToDatabase() method (which, as I've already mentioned, returns an ArrayList). 我想要的是通过connectToDatabase()方法的返回值实例化ContactControl类中的ArrayList(正如我已经提到的,该方法返回一个ArrayList)。

However, I keep getting an exception. 但是,我一直在例外。 It's not connecting to the database. 它没有连接到数据库。 It connects when I run the main method that I placed in the DatabaseUtility class, but when I run the main method from the ContactControl class, I get an exception. 当我运行放置在DatabaseUtility类中的main方法时,它会连接,但是当我从ContactControl类中运行main方法时,则会出现异常。

My code is below: 我的代码如下:

Contact class: 联系人类别:

package contactbook;

import java.io.IOException;
import java.io.ObjectStreamException;
import java.util.Date;

public class Contact {
    private int contactId;
    private String lastName;
    private String firstName;


    private String address;
    private String city;
    private String state;
    private String zip;
    private String picture;
    private String dob;

    public Contact()
    {
        contactId = 0;
        lastName =  "Doe";
        firstName = "John";
        dob = "01/01/1997";
        address = "123 ABC Dr.";
        city = "Pensacola";
        state = "FL";
        zip = "12345";
        picture = "default1.gif";
    }

    public Contact(int contactId, String lastName, String firstName, String address, String city, String state, String zip, String picture, String dob)
    {
        this.contactId = contactId;
        this.lastName = lastName;
        this.firstName = firstName;
        this.address = address;
        this.city = city; 
        this.state = state;
        this.zip = zip;
        this.picture = picture;
        this.dob = dob;
    }

    //setters
    public void setContactId(int contactId)
    {

    }

    public void setLastName(String lastName)
    {
        this.lastName = lastName;
    }

    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }

    public void setAddress(String address)
    {
        this.address = address;
    }

    public void setCity(String city)
    {
        this.city = city;
    }

    public void setState(String state)
    {
        this.state = state;
    }

    public void setZip(String zip)
    {
        this.zip = zip;
    }

    public void setPicture(String picture)
    {
        this.picture = picture;
    }

    public void setDob(String dob)
    {
        this.dob = dob;
    }

    //getters

    public int getContactId()
    {
        return contactId;
    }

    public String getLastName()
    {
        return lastName;
    }

    public String getFirstName()
    {
        return firstName;
    }

    public String getAddress()
    {
        return address;
    }

    public String getCity()
    {
        return city;
    }

    public String getState()
    {
        return state;
    }

    public String getZip()
    {
        return zip;
    }

    public String getPicture()
    {
        return picture;
    }

    public String getDob()
    {
        return dob;
    }

}

DatabaseUtility class: DatabaseUtility类:

package contactbook;



import java.io.IOException;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Properties;

public class DataBaseUtility {


public ArrayList<Contact> connectToDatabase() throws Exception { 
    ArrayList<Contact> contacts = new ArrayList<Contact>();
try
    {
      // Step 1: "Load" the JDBC driver
      Class.forName("org.apache.derby.jdbc.ClientDriver"); 

      // Step 2: Establish the connection to the database 
      String url = "jdbc:derby://localhost:1527/ContactBook"; 
      Connection conn = DriverManager.getConnection(url,"app","app");  
      System.out.println("Connected!");
      Statement stat = null;
      stat = conn.createStatement();
        ResultSet rs = stat.executeQuery("SELECT * FROM PERSON");
        int id = 1;
      while(rs.next())
      {

          Contact contact = new Contact();
          contact.setContactId(id);
          System.out.println(id);
          String lastName = rs.getString("lastName");
          System.out.println(lastName);
          contact.setLastName(lastName);
          String firstName = rs.getString("firstName");
          System.out.println(firstName);
          contact.setFirstName(firstName);
          String address = rs.getString("address");
          System.out.println(address);
          contact.setAddress(address);
          String city = rs.getString("city");
          System.out.println(city);
          contact.setCity(city);
          String state = rs.getString("state");
          System.out.println(state);
          contact.setState(state);
          String zip = rs.getString("zip");
          System.out.println(zip);
          contact.setZip(zip);
          String picture = rs.getString("picture");
          System.out.println(picture);
          contact.setPicture(picture);
          Date dob = rs.getDate("dob");
          System.out.println(dob);
          contact.setDob("" + dob);
          contacts.add(contact);
          System.out.println("");
          contacts.add(contact);
          id++;
      }
    }
    catch (Exception e)
    {
      System.err.println("D'oh! Got an exception!"); 
      System.err.println(e.getMessage()); 
    } 
      return contacts;
  } 

public static void main(String[] args)
{
    DataBaseUtility dbu = new DataBaseUtility();
    try
    {
        dbu.connectToDatabase();
    }
    catch(Exception e)
    {
        e.getMessage();
    }

}
} 

ContactControl class: ContactControl类:

package contactbook;

import java.util.ArrayList;


public class ContactControl {
    private DataBaseUtility dbu;
    private ArrayList<Contact> contacts;

    public ArrayList<Contact> createContacts() throws Exception
    {
        try
        {
            contacts = dbu.connectToDatabase();
        }
        catch(Exception e)
        {
            System.out.println("Error!");
        }

        return contacts;
    }

    public Contact getContact(int id)
    {
        Contact tact = new Contact();
        for(Contact c : contacts)
        {
            if(id == c.getContactId())
            {
                tact = c;
            }
        }
            return tact;
    }

    public static void main(String[] args)
    {
        ContactControl cc = new ContactControl();
        ArrayList<Contact> tacts = new ArrayList<>();
        try
        {
            tacts = cc.createContacts();
        }
        catch(Exception e)
        {
            System.out.println("Uh oh! Problem!");
        }


    }

}

Whenver I run the main method of the ContactControl class, I get the "Error!" 每当我运行ContactControl类的main方法时,都会出现“错误!”。 message that you see in the try-catch block. 您在try-catch块中看到的消息。

I think the issue is that you're calling a null object in your ContactControl class. 我认为问题在于您在ContactControl类中调用了一个空对象。

contacts = dbu.connectToDatabase();

dbu is not initialized and basically it's null thus the NullPointerException. dbu未初始化,因此基本上为null,因此为NullPointerException。 Since you're hiding actual exception messages from yourself with some custom messages you wouldn't see it. 由于您使用一些自定义消息来隐藏实际的异常消息,因此您不会看到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我在使用我在另一个 Java 类中创建的类时遇到问题 - I'm having trouble using a class I have created in another class in Java 我只是很难从我的 Java 课程中理解课程材料 - I'm just having hard time understanding the class material from my java class 我在 Heroku 上部署基于 Java 的应用程序时遇到问题 - I'm having an Issue Deploying a Java based application on Heroku 我有一个比较问题 - I'm having a compare issue 我在用Java从磁盘加载对象时遇到问题 - I'm having problems loading objects from disk in Java 我无法从Java中的方法返回列表 - I'm having trouble returning a List from a method in Java java,从另一个类发出调用方法 - java, issue calling method from another class 我对android和Java非常陌生。 我想从一个类到另一个类获取字符串数组 - I,m very new to android and Java. I want to get a string array from one class to another class 在与Oracle数据库连接的Java应用程序中发现问题,SQLException:Io异常:从读取调用中减去一个,我该如何解决? - Found issue in java application connecting with oracle database,SQLException: Io exception: Got minus one from a read call ,how I can solve it? 我在Sco OpenServer版本5.0.6上运行Java应用程序时遇到问题 - I'm having issue when i run my java application on a Sco OpenServer Release 5.0.6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM