JDBC中添加数据成功后,如何返回主键id
@Test
public void test02() throws Exception
{
Class
.forName("com.mysql.jdbc.Driver");
String url
= "jdbc:mysql://localhost:3306/test";
String user
= "root";
String password
= "123456";
Connection conn
= DriverManager
.getConnection(url
, user
, password
);
String sql
= "insert into tb_user(name, age, birthday) values(?,?,?)";
PreparedStatement pst
= conn
.prepareStatement(sql
, Statement
.RETURN_GENERATED_KEYS
);
pst
.setString(1, "qqqq");
pst
.setInt(2, 15);
pst
.setDate(3, new java.sql.Date(new Date().getTime()));
int count
= pst
.executeUpdate();
ResultSet rs
= pst
.getGeneratedKeys();
if (rs
.next()) {
System
.out
.println("主键值为:" + rs
.getObject(1));
}
System
.out
.println(count
> 0 ? "添加成功!" : "添加失败");
rs
.close();
pst
.close();
conn
.close();
}
转载请注明原文地址: https://mac.8miu.com/read-504327.html