jdbc java數據庫連接 7)獲取插入數據的自增長值


我們創建一個sql表,里面的數據往往都會有自增長值。

那么,我們用jdbc插入數據的時候,要想同時獲得這個增長值。

 

   代碼:

/**
 * 
 * 這是插入一條數據的同時,獲取該數據的則增長列的值(該例子的自增長列是id)
 * 
 * @author LZL
 * 
 */
public class Auto_Increment {

    private static Connection conn = null;
    private static PreparedStatement stsm = null;
    private static ResultSet rs = null;

    @Test
    public void testGetAutoIncrement() {
        try {
            // 1:創建連接
            conn = Jdbcutil.getConnection();

            // 2:設置sql預編譯語句
            String sql = "INSERT INTO person (NAME,sex,age) VALUES (?,?,?);";

            // 3:執行sql預編譯語句(同時在參數中指定自增列)
            stsm = conn.prepareStatement(sql,
                    PreparedStatement.RETURN_GENERATED_KEYS);

            // 4:設置參數值
            stsm.setString(1, "王五");
            stsm.setString(2, "男");
            stsm.setInt(3, 22);

            // 5:發送參數,執行sql
            stsm.executeUpdate();

            // 6:執行完上面的更新數據操作后,獲取自增長列
            rs = stsm.getGeneratedKeys();
            // 7:輸出該數據對應的自增長列的值
            if (rs.next()) {
                System.out.println("剛才添加的數據的自增長列值是:" + rs.getInt(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
        }

        Jdbcutil.close(conn, stsm, rs);

    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM