您的位置:首页 > 其它

向某个表插入数据的时候,获取到插入记录的 id

2013-09-17 00:00 549 查看

今天要做当向某个表插入数据的时候,获取到插入记录的 id
没什么可说的,直接贴代码

package fetcher;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class BooksDAO {
static final String driver = "com.mysql.jdbc.Driver";
static final String url = "jdbc:mysql://localhost:3306/ts?useUnicode=true&characterEncoding=utf-8";//
static final String user = "root";
static final String password = "ok";

public int insertBooks(String title, String author, String description) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 加载驱动程序
Class.forName(driver);
// 连续数据库
conn = DriverManager.getConnection(url, user, password);
String sql = "INSERT INTO books (title ,author ,description )VALUES (?,?,?);";
pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, title);
pstmt.setString(2, author);
pstmt.setString(3, description);

pstmt.executeUpdate();
// 获得自动生成的键值
rs = pstmt.getGeneratedKeys();
rs.next();
int bookid = rs.getInt(1);
if (bookid > 0)
return bookid;

rs.close();
pstmt.close();
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息