• 获取自动生成的主键


    package pers.mjn.return_pk;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.Statement;
    
    import org.junit.Test;
    
    import pers.mjn.util.JdbcUtil;
    
    // 获取自动生成的主键
    public class ReturnPKTest {
    
    	// Statement方式
    	@Test
    	public void testStatement() throws Exception {
    		String sql = "INSERT INTO t_student (name, age) VALUES ('AA', 23)";
    		Connection conn = JdbcUtil.getConn();
    		Statement st = conn.createStatement();
    		//-----------------------------------
    		// 设置可以获取自动生成的主键
    		st.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
    		// 去获取自动生成的主键
    		ResultSet rs = st.getGeneratedKeys();
    		if(rs.next()) {
    			Long id = rs.getLong(1);	// 获取第一列
    			System.out.println(id);
    		}
    		JdbcUtil.close(conn, st, rs);
    	}
    	
    	// PreparedStatement 方式
    	@Test
    	public void testPreparedStatement() throws Exception {
    		String sql = "INSERT INTO t_student (name, age) VALUES (?, ?)";
    		Connection conn = JdbcUtil.getConn();
    		// ---------------------------------------------------------------
    		// 设置可以获取自动生成的主键
    		PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
    		ps.setString(1, "XX");
    		ps.setInt(2, 28);
    		ps.executeUpdate();
    		// 去获取自动生成的主键
    		ResultSet rs = ps.getGeneratedKeys();
    		if(rs.next()) {
    			Long id = rs.getLong(1);	// 获取第一列
    			System.out.println(id);
    		}
    		JdbcUtil.close(conn, ps, null);
    	}
    }
    

      

  • 相关阅读:
    hdu4291 A Short problem
    UVA
    HDU
    Be Geeks!
    HDU
    hdu6559 The Tower
    胜利大逃亡(续) + Maze
    Stealing Harry Potter's Precious
    hdu5172 GTY's gay friends
    Log Concave Sequences Gym
  • 原文地址:https://www.cnblogs.com/mjn1/p/11196975.html
Copyright © 2020-2023  润新知