我目前在Customer.java
课程中使用此方法,并希望在我的createCustomerAccount
课程中使用此方法。
public String generateCustomerId(){
String customerId=new String();
int a,b,c;
try {
ResultSet rs=db.read(db.connect().prepareStatement("SELECT idCustomer FROM Customer"));
db.disconnect();
if(rs.next()==false){
customerId="ACC000";
}
else{
while(rs.next()){}
customerId=rs.getString("idDiscount");
a=customerId.charAt(3);
b=customerId.charAt(4);
c=customerId.charAt(5);
if(c<9){
c++;
customerId="ACC"+a+b+c;
}else if(b<9){
c=0;
b++;
customerId="ACC"+a+b+c;
}else{
b=0;
c=0;
a++;
customerId="ACC"+a+b+c;
}
}
} catch (SQLException ex) {
Logger.getLogger(Customer.class.getName()).log(Level.SEVERE, null, ex);
}
return customerId;
}
我的createCustomerAccount
课程目前看起来像这样:
private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {
AccountName = txtAccHolder.getText();
contactName = txtContact.getText();
phone = txtPhone.getText();
email = txtEmail.getText();
address = txtAddress.getText();
String sql = ("INSERT INTO customer(idCustomer,accountName,contactName,address,PhoneNo,email) VALUES ('"+id+ "', '"+AccountName+"', '"+contactName+"','"+address+"','"+phone+"','"+email+"')");
try {
db.write(db.connect().prepareStatement(sql));
} catch (SQLException ex) {
Logger.getLogger(Customer.class.getName()).log(Level.SEVERE, null, ex);
} finally {
db.disconnect();
}
}
我可以在单独的课程中使用我的按钮方法中的generateCustomerId
方法吗?
答案 0 :(得分:0)
因此,您使用的SQL会选择所有客户的ID。也许您正在尝试选择“AC”+(max(id)+ 1)。我不确定这是在做什么。
您绝对可以创建Customer类的实例并在createCustomerAccount中调用该方法,如下所示:
Customer customer = new Customer();
String customerId = customer.generateCustomerId();
或者你可以使方法静态并按如下方式调用它:
String customerId = Customer.generateCustomerId();
但是,我个人认为最好在数据库中生成id,如下所示:
CREATE TABLE account (
id SERIAL NOT NULL,
name CHARACTER VARYING(255) NOT NULL
);
CREATE TABLE customer (
id SERIAL NOT NULL,
name CHARACTER VARYING(255) NOT NULL,
id_account INTEGER NOT NULL REFERENCES account(id) ON DELETE RESTRICT
);
INSERT INTO customer(name, id_account) VALUES ('customer name', 7) RETURNING id;