public class Demo4 {
/*
create table test1
(
id int primary key auto_increment,
name varchar(20)
);
*/
@Test
public void test1()
{
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try
{
conn = JdbcUtils.getConnection();
String sql = "insert into test1(name) values(?)";
st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); //默认也会返回keys
st.setString(1, "kevin");
st.executeUpdate();
rs = st.getGeneratedKeys();//插入后获得主键值
while(rs.next())
{
System.out.println("id: " + rs.getInt(1));
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
JdbcUtils.release(conn, st, rs);
}
}
@Test
public void test2()
{
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try
{
conn = JdbcUtils.getConnection();
String sql = "select * from test1";
st = conn.prepareStatement(sql);
rs = st.executeQuery();
while(rs.next())
{
System.out.println("id: " + rs.getInt("id"));
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
JdbcUtils.release(conn, st, rs);
}
}
}