어떤 테이블에 데이터를 삽입할 때 삽입 기록의 id를 가져옵니다

오늘 어떤 테이블에 데이터를 삽입할 때 삽입된 기록의 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;  
}  

}

좋은 웹페이지 즐겨찾기