JDBC之获取插入语句返回的主键

该获取主键并不是绝对的,也和具体的数据库实现的驱动有关。

package cn.itcast.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Test;

/**
 * 测试JDBC中的几个其他API
 */
public class OtherApi {

	/**
	 * 测试create方法
	 * @throws SQLException
	 */
	@Test
	public void testCreate() throws SQLException {
		System.out.println(create());
	}
	
	/**
	 * 测试从数据库读取数据
	 * @throws SQLException
	 * @throws InterruptedException
	 */
	@Test
	public void testRead() throws SQLException, InterruptedException {
		read();
	}
	
	/**
	 * 读取数据库中的数据
	 * @throws SQLException
	 * @throws InterruptedException
	 */
	static void read() throws SQLException, InterruptedException {
		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		
		try {
			//建立连接
			conn = JdbcUtils.getConnection();
			//创建语句
			st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
					ResultSet.CONCUR_UPDATABLE);
			//执行语句
			rs = st.executeQuery("select id, name, money, birthday  from user where id < 5");
			
			//处理结果
			while(rs.next()) {
				int id = rs.getInt("id");
				System.out.println("show"  + id + "...");
				Thread.sleep(10000);
				System.out.println(id +"\t" + rs.getObject("name") + "\t"
						+ rs.getObject("birthday") + "\t"
						+ rs.getObject("money"));
			}
		} finally {
			JdbcUtils.free(rs, st, conn);
		}
	}
	
	/**
	 * 向数据库中插入语句
	 * @return
	 * @throws SQLException
	 */
	static int create() throws SQLException {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		try {
			//建立连接
			conn = JdbcUtils.getConnection();
			//创建语句
			String sql = "insert into user(name,birthday, money) values ('name2 gk', '1987-01-01', 400) ";
			//通过传入第二个参数,就会产生主键返回给我们
			ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			ps.executeUpdate();
			
			//返回的结果集中包含主键,注意:主键还可以是UUID,
			//复合主键等,所以这里不是直接返回一个整型
			rs = ps.getGeneratedKeys();
			int id = 0;
			if(rs.next()) {
				id = rs.getInt(1);
			}
			return id;
		} finally{
			JdbcUtils.free(rs, ps, conn);
		}
	}
	
}


你可能感兴趣的:(JDBC)