JDBC_获取插入记录的主键值

<span style="font-size:24px;">package src.com.JDBC2DAO.java;

import static org.junit.Assert.*;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import org.junit.Test;

public class JDBCTest {
	/**
	 * 取得数据库自动生成的主键
	 */
	@Test
	public void testGetKeyValue() {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			connection = JDBCTools.getConnection();
			String sql = "INSERT INTO customers(name,email,birth) VALUES(?,?,?)";

			//preparedStatement = connection.prepareStatement(sql);
			//生成preparedStatment对象
			preparedStatement = connection.prepareStatement(sql,
					Statement.RETURN_GENERATED_KEYS);
			preparedStatement.setString(1, "ABCD");
			preparedStatement.setString(2, "[email protected]");
			preparedStatement.setDate(3,
					new Date(new java.util.Date().getTime()));
			preparedStatement.executeUpdate();
			//通过.getGeneratedKeys()获取包含了新生成的主键的resultSet对象
			//在ResultSet中只有一列GENERATED_KEYS,用于存放新生成的主键值
			ResultSet rs=preparedStatement.getGeneratedKeys();
			if (rs.next()) {
				System.out.println(rs.getObject(1));
			}
			ResultSetMetaData rsmd=rs.getMetaData();
			for (int i = 0; i < rsmd.getColumnCount(); i++) {
				System.out.println(rsmd.getCatalogName(i+1));
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JDBCTools.releaseDB(null, preparedStatement, connection);
		}
	}
}
</span>

你可能感兴趣的:(jdbc)