我应该使用什么而不是stmt.executeUpdate()?

时间:2016-09-22 10:07:00

标签: java sql jdbc

当我使用stmt.executeUpdate()并且如果我使用executeQuery时它不会返回我刚插入到db中的记录我在创建stmt对象时设置了coccurency和type

我的桌子是

create Table Customer(
Customer_ID int,
Age int,
Contact_No varchar(20),
First_Name varchar(20),
Last_Name varchar(20),
PRIMARY KEY(Customer_ID)
);

create Table Customer_Address(
Customer_ID int,
Address_Line1 varchar(50),
Address_Line2 varchar(50),
City varchar(20),
Pincode int,
State varchar(25),
PRIMARY KEY(Customer_ID,Address_Line1)
);

我的Java代码:

try {

    st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    st.executeUpdate("insert into Customer values(Default,"+age+",'"+contact_no+"','"+first+"','"+last+"')");

    ResultSet set = st.executeQuery("select Customer_ID from Customer where First_Name = '"+first+"' and Last_Name ='"+last+"' and contact_no ='"+contact_no+")");
    int id = set.getInt(1);
    st.executeUpdate("insert into Customer_Address Values("+id+",'"+add1+"','"+add2+"','"+city+"',"+pincode+",'"+state+"')");
}
catch (SQLException ex) {
    Logger.getLogger(Screen1.class.getName()).log(Level.SEVERE, null, ex);
}

2 个答案:

答案 0 :(得分:0)

替换

ResultSet set = st.executeQuery("select Customer_ID from Customer where First_Name = '"+first+"' and last ='"+last+"' and contact_no ='"+contact_no+")");

ResultSet set = st.executeQuery("select Customer_ID from Customer where First_Name = '"+first+"' and last ='"+last+"' and contact_no ='"+contact_no+"')");

答案 1 :(得分:0)

如果您只想要插入行的ID,请使用Statement.RETURN_GENERATED_KEYS,如下所示:

st.executeUpdate("INSERT INTO ...", Statement.RETURN_GENERATED_KEYS);
int id;
try (ResultSet rs = st.getGeneratedKeys()) {
    rs.next();
    id = rs.getInt(1);
}

// ...
相关问题