package com.atguigu.jdbc;
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,);
//使用重载的prepareStatement(sql,flag)来生成preparedStatement对象
preparedStatement=connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, "柴玉霞");
preparedStatement.setString(2, "[email protected]");
preparedStatement.setDate(3, new Date(new java.util.Date().getTime()));
preparedStatement.executeUpdate();
//通过.getGeneratedKeys()获取包含了新生的主键的ResutlSet对象
//在ResultSet中只有一列GENERATED_DEY,用于存放新生成的主键值
ResultSet rs=preparedStatement.getGeneratedKeys();
if(rs.next()){
System.out.println(rs.getObject(1));
}
ResultSetMetaData resultSetMetaData=rs.getMetaData();
for(int i=0;i<resultSetMetaData.getColumnCount();i++){
System.out.println(resultSetMetaData.getColumnName(i+1));
}
}catch(Exception e){
e.printStackTrace();
}finally{
JDBCTools.release(null, preparedStatement, connection);
}
}
}