获得数据库自动生成的主键与调用存储过程
作者:网络转载 发布时间:[ 2013/7/24 10:13:25 ] 推荐标签:
获取主键
注:此参数仅对insert操作有效。
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try{
conn = JdbcUtils.getConnection();
String sql = "insert into test(name) values('aaa')";
//出入Statement.RETURN_GENERATED_KEYS参数是要返回生成主键,默认是返回的,写上 为了以后换成别的数据库也行。
st = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
st.executeUpdate();
//调用getGeneratedKeys方法得到生成的键
rs = st.getGeneratedKeys();
if(rs.next()){
//获取主键
System.out.println(rs.getInt(1));
}
}finally{
JdbcUtils.release(conn, st, rs);
}
}
调用存储过程
在MySQL中创建存储过程
delimiter $$
CREATE PROCEDURE demoSp(IN inputParamVARCHAR(255), INOUT inOutParam varchar(255))
BEGIN
SELECT CONCAT('zyxw---', inputParam) intoinOutParam;
END $$
delimiter ;
//调用
public class Demo {
public static void main(String[] args) throws SQLException {
Connection conn = null;
CallableStatement st = null;
ResultSet rs = null;
try{
conn = JdbcUtils.getConnection();
//调用存储过程
st = conn.prepareCall("{call demoSp(?,?)}");
//替换占位符
st.setString(1, "aaaaa");
//第二个为类型
st.registerOutParameter(2, Types.VARCHAR);
st.execute();
System.out.println(st.getString(2));
}finally{
JdbcUtils.release(conn, st, rs);
}
}
}
结果集的滚动
ResultSet提供了对结果集进行滚动的方法:
next():移动到下一行
Previous():移动到前一行
absolute(int row):移动到指定行
beforeFirst():移动resultSet的前面。
afterLast() :移动到resultSet的后面。
例:获取后一条数据
afterLast();
Previous();

sales@spasvo.com