String accountQuery = "insert into Account (accountNumber,currentBalance,type,personId) values (?,?,?,?);";
PreparedStatement accountPs = null;
try {
// These are my prepare Statements for my queries
accountPs = conn.prepareStatement(accountQuery);
// accountPs.setInt(1, personId.getPersonId());
accountPs.setInt(1, accountHolder.getAccountNumber());
accountPs.setDouble(2, accountHolder.getCurrentBalance());
accountPs.setString(3, accountHolder.getType());
accountPs.setInt(4, personId.getPersonId());
accountPs.executeUpdate();
accountPs.close();
conn.close();
}
How can I check if accountNumber (non primary key) already exists in my database? Whenever I run my program more than once, it’ll populate my tables with repeated data because accountNumber isn’t a primary key and because my accountId is an auto_increment. Note I cannot change any of the contents of the table.
create table Account(
accountId int primary key not null auto_increment,
accountNumber int not null,
currentBalance double not null,
type varchar(1) not null,
personId int not null,
foreign key(personId) references Person(personId)
);
2
Answers
If I understand your question, the simplest thing I can think of is to add a unique constraint to your table for account_number. Like,
If you want to avoid an exception, you need to check if this number is already here and if not add it.
Probably somehow like this: