今天要作當向某個表插入數據的時候,獲取到插入記錄的 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;
}
}