java.sql.SQLException:没有这样的列

sil*_*lea 1 java sql sqlite

我被分配了一个使用sqlite演示CRUD操作的任务。当我尝试从数据库中检索项目时,我的ResultSet似乎没有“ id”列。我很沮丧。

这是我的ContactRepository类。

public class ContactRepositoryJDBC implements ContactRepository {

    private static Connector connector = new Connector();

    ...

    public Contact getById(int id) throws SQLException {
        Contact contact = null;

        try (Connection conn = connector.getConnection();
            PreparedStatement statement = conn
                    .prepareStatement(SQL.GET_CONTACT_BY_ID)) {
            statement.setInt(1, id);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    contact = new Contact();
                    contact.setId(resultSet.getInt("id"));
                    contact.setFirstName(resultSet.getString("first_name"));
                    contact.setSurname(resultSet.getString("surname"));
                    contact.setHomeNumber(resultSet.getString("home_number"));
                    contact.setCellNumber(resultSet.getString("cell_number"));
                    contact.setEmail(resultSet.getString("email"));
                }
            }
        }

        if (contact == null) {
            System.out.print("no contact with id " + id + " found : ");
        }
        return contact;
    }

...

}
Run Code Online (Sandbox Code Playgroud)

我将单独的类用于我的sql语句

public class SQL {

...

public static final String GET_CONTACT_BY_ID = "SELECT first_name, surname, home_number, cell_number, email FROM Contact WHERE id = ?";

...

}
Run Code Online (Sandbox Code Playgroud)

我得到一个SQLException“没有这样的列ID”

Exception in thread "main" java.sql.SQLException: no such column: 'id'
at org.sqlite.RS.findColumn(RS.java:121)
at org.sqlite.RS.getInt(RS.java:293)
at net.phonebook.repository.ContactRepositoryJDBC.getById(ContactRepositoryJDBC.java:59)
at net.phonebook.model.app.App.main(App.java:31)    
Run Code Online (Sandbox Code Playgroud)

编辑:

接触模型类

public class Contact {

    private int id;
    private String firstName;
    private String surname;
    private String homeNumber;
    private String cellNumber;
    private String email;

    public Contact(String firstName, String surname, String homeNumber,
            String cellNumber, String email) {
        this.firstName = firstName;
        this.surname = surname;
        this.homeNumber = homeNumber;
        this.cellNumber = cellNumber;
        this.email = email;
    }

    public Contact() {

    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    ... getters and setter for everything else
}
Run Code Online (Sandbox Code Playgroud)

laa*_*lto 5

您的选择不包括该列id,因此不在结果集中。将其添加到选择中:

public static final String GET_CONTACT_BY_ID = "SELECT id, first_name, surname, home_number, cell_number, email FROM Contact WHERE id = ?";
Run Code Online (Sandbox Code Playgroud)