`
haoningabc
  • 浏览: 1478013 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

insert返回插入的id

    博客分类:
  • sql
 
阅读更多
public long insertFetchIdL(String sql)
  throws SQLException
{
  Connection conn = getConnection(true, true);
  if (null != conn)
  {
    PreparedStatement prepareStatement = null;
    ResultSet generatedKeys = null;
    try
    {
      prepareStatement = conn.prepareStatement(sql, 1);
      prepareStatement.execute();
      generatedKeys = prepareStatement.getGeneratedKeys();
      long id = -1L;
      if (generatedKeys.next())
      {
        id = generatedKeys.getLong(1);
      }
      long l1 = id;

      return l1;
    }
    catch (SQLException e)
    {
    }
    catch (Exception e)
    {
    }
    finally
    {
      conn.close();
      try
      {
        if (null != generatedKeys)
        {
          generatedKeys.close();
        }
        if (prepareStatement != null)
        {
          prepareStatement.close();
        }
      }
      catch (SQLException e)
      {
        logger.warn("" + sql, e);
        throw e;
      }
    }
  }

  long t = System.currentTimeMillis();
  try
  {
    SimpleRowSet r = ifi(sql);
    if (logger.isDebugEnabled())
    {
      logger.debug("TakeTime:" + sql + "\t" + (System.currentTimeMillis() - t));
    }
    if (r.next())
    {
      return r.getLong(1);
    }
    return -1L;
  }
  catch (Exception e)
  {
    throw new DBException(e.getMessage(), e);
  }
}
分享到:
评论
Global site tag (gtag.js) - Google Analytics