List of usage examples for java.sql PreparedStatement getGeneratedKeys
ResultSet getGeneratedKeys() throws SQLException;
Statement
object. From source file:org.wso2.carbon.identity.authorization.core.jdbc.dao.JDBCPermissionDAO.java
@Override protected void insert(PreparedStatement stmt, ResultSet res, Connection connection) throws SQLException, UserStoreException { String sql = "INSERT INTO UM_PERMISSION (UM_RESOURCE_ID, UM_MODULE_ID, UM_TENANT_ID, UM_ACTION) VALUES(?,?,?,?) "; stmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); byte count = 0; stmt.setString(++count, getResourceId()); stmt.setInt(++count, getModuleId()); stmt.setInt(++count, getTenantId()); stmt.setString(++count, getAction()); int resCount = stmt.executeUpdate(); if (resCount == 0) { String error = "Insertion faild for the permission"; log.error(error);/* w w w .j ava 2s.c o m*/ throw new UserStoreException(error); } res = stmt.getGeneratedKeys(); if (res.next()) { setPermissionId(res.getInt(1)); } }
From source file:org.wso2.carbon.device.mgt.group.core.dao.GroupDAOImpl.java
@Override public int addGroup(DeviceGroup deviceGroup, int tenantId) throws GroupManagementDAOException { PreparedStatement stmt = null; ResultSet rs;//from w w w .ja v a 2 s . c o m int groupId = -1; try { Connection conn = GroupManagementDAOFactory.getConnection(); String sql = "INSERT INTO DM_GROUP(DESCRIPTION, NAME, DATE_OF_ENROLLMENT, DATE_OF_LAST_UPDATE, " + "OWNER, TENANT_ID) VALUES (?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(sql); stmt.setString(1, deviceGroup.getDescription()); stmt.setString(2, deviceGroup.getName()); stmt.setLong(3, new Date().getTime()); stmt.setLong(4, new Date().getTime()); stmt.setString(5, deviceGroup.getOwner()); stmt.setInt(6, tenantId); stmt.executeUpdate(); rs = stmt.getGeneratedKeys(); if (rs.next()) { groupId = rs.getInt(1); } return groupId; } catch (SQLException e) { String msg = "Error occurred while adding deviceGroup " + "'" + deviceGroup.getName() + "'"; log.error(msg, e); throw new GroupManagementDAOException(msg, e); } finally { GroupManagementDAOUtil.cleanupResources(stmt, null); } }
From source file:iddb.runtime.db.model.dao.impl.mysql.UserDAOImpl.java
@Override public void save(User user) { String sql;/*from w ww . j a v a 2 s .c o m*/ if (user.getKey() == null) { sql = "insert into user (loginid, roles, updated, created, password) values (?,?,?,?,?)"; } else { sql = "update user set loginid = ?," + "roles = ?," + "updated = ? where id = ? limit 1"; } Connection conn = null; try { conn = ConnectionFactory.getMasterConnection(); PreparedStatement st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); st.setString(1, user.getLoginId()); st.setString(2, Functions.join(user.getRoles(), ",")); st.setTimestamp(3, new Timestamp(new Date().getTime())); if (user.getKey() != null) { st.setLong(4, user.getKey()); } else { st.setTimestamp(4, new Timestamp(new Date().getTime())); st.setString(5, user.getPassword()); } st.executeUpdate(); if (user.getKey() == null) { ResultSet rs = st.getGeneratedKeys(); if (rs != null && rs.next()) { user.setKey(rs.getLong(1)); } else { logger.warn("Couldn't get id for user {}", user.getLoginId()); } } } catch (SQLException e) { logger.error("Save: {}", e); } catch (IOException e) { logger.error("Save: {}", e); } finally { try { if (conn != null) conn.close(); } catch (Exception e) { } } }
From source file:org.wso2.carbon.device.mgt.core.dao.impl.ApplicationDAOImpl.java
@Override public List<Integer> removeApplications(List<Application> apps, int tenantId) throws DeviceManagementDAOException { Connection conn = null;/*w w w . j av a2s . c o m*/ PreparedStatement stmt = null; ResultSet rs = null; List<Integer> applicationIds = new ArrayList<>(); try { conn = this.getConnection(); conn.setAutoCommit(false); stmt = conn.prepareStatement("DELETE DM_APPLICATION WHERE APP_IDENTIFIER = ? AND TENANT_ID = ?", new String[] { "id" }); for (Application app : apps) { stmt.setString(1, app.getApplicationIdentifier()); stmt.setInt(2, tenantId); stmt.addBatch(); } stmt.executeBatch(); rs = stmt.getGeneratedKeys(); if (rs.next()) { applicationIds.add(rs.getInt(1)); } return applicationIds; } catch (SQLException e) { try { if (conn != null) { conn.rollback(); } } catch (SQLException e1) { log.warn("Error occurred while roll-backing the transaction", e); } throw new DeviceManagementDAOException("Error occurred while removing bulk application list", e); } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } }
From source file:com.microsoftopentechnologies.azchat.web.dao.UserDAOImpl.java
/** * This method executes adds new user query on the azure SQL user table. * //w ww.j a va2s .c o m * @return userEntity */ public UserEntity saveNewUser(UserEntity user) throws Exception { LOGGER.info("[UserDAOImpl][saveNewUser] start "); int userId = 0; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = AzureChatUtils.getConnection(AzureChatUtils.buildConnectionString()); preparedStatement = connection.prepareStatement(AzureChatSQLConstants.SAVE_NEW_USER, Statement.RETURN_GENERATED_KEYS); preparedStatement = generatePreparedStatement(preparedStatement, user); preparedStatement.executeUpdate(); resultSet = preparedStatement.getGeneratedKeys(); if (resultSet.next()) { userId = resultSet.getInt(1); } } catch (Exception e) { LOGGER.error( "Exception occurred while executing save user query on azure SQL table. Exception Message : " + e.getMessage()); throw new AzureChatSystemException( "Exception occurred while executing save user query on azure SQL table. Exception Message : " + e.getMessage()); } finally { AzureChatUtils.closeDatabaseResources(preparedStatement, resultSet, connection); } user.setUserID(userId); LOGGER.info("[UserDAOImpl][saveNewUser] end "); return user; }
From source file:net.mindengine.oculus.frontend.service.project.JdbcProjectDAO.java
@Override public Long createProject(Project project) throws Exception { PreparedStatement ps = getConnection().prepareStatement( "insert into projects (name, description, path, parent_id, icon, author_id, date) values (?,?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); ps.setString(1, project.getName());// w ww . ja va2s.c om ps.setString(2, project.getDescription()); ps.setString(3, project.getPath()); ps.setLong(4, project.getParentId()); ps.setString(5, project.getIcon()); ps.setLong(6, project.getAuthorId()); ps.setTimestamp(7, new Timestamp(project.getDate().getTime())); ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); Long projectId = null; if (rs.next()) { projectId = rs.getLong(1); } if (project.getParentId() > 0) { // Increasing the parents project subprojects_count var update("update projects set subprojects_count = subprojects_count+1 where id = :id", "id", project.getParentId()); } return projectId; }
From source file:org.hawkular.inventory.impl.tinkerpop.sql.impl.SqlGraph.java
@Override public synchronized Vertex addVertex(Object id) { return withSavePoint(() -> { PreparedStatement stmt = statements.getAddVertex(); if (stmt.executeUpdate() == 0) { return null; }//w w w .j a v a 2 s .com try (ResultSet rs = stmt.getGeneratedKeys()) { Vertex ret = cache(statements.fromVertexResultSet(rs)); dirty = true; return ret; } }); }
From source file:com.jfinal.plugin.activerecord.Model.java
/** * Get id after save method./* w w w . ja va2 s . c om*/ */ private void getGeneratedKey(PreparedStatement pst, TableInfo tableInfo) throws SQLException { String pKey = tableInfo.getPrimaryKey(); if (get(pKey) == null || DbKit.dialect.isOracle()) { ResultSet rs = pst.getGeneratedKeys(); if (rs.next()) { Class colType = tableInfo.getColType(pKey); if (colType == Integer.class || colType == int.class) set(pKey, rs.getInt(1)); else if (colType == Long.class || colType == long.class) set(pKey, rs.getLong(1)); else set(pKey, rs.getObject(1)); // It returns Long object for int colType rs.close(); } } }
From source file:edu.corgi.uco.UserBean.java
public String add() throws SQLException, EmailException { if (dataSource == null) { throw new SQLException("DataSource is null"); }//ww w. ja va2 s . co m Connection connection = dataSource.getConnection(); if (connection == null) { throw new SQLException("Connection"); } try { Random rand = new Random(); int randomNum = rand.nextInt((999999999 - 100000000) + 1) + 100000000; PreparedStatement addUser = connection.prepareStatement( "insert into UserTable (email, ucoID, password, firstName, lastName,authKey) values (?, ?, ?, ?, ?,?)", Statement.RETURN_GENERATED_KEYS); addUser.setString(1, email); addUser.setString(2, ucoId); addUser.setString(3, password); addUser.setString(4, firstName); addUser.setString(5, lastName); addUser.setInt(6, randomNum); addUser.executeUpdate(); ResultSet results = addUser.getGeneratedKeys(); //for whatever really fun reason it says userid is not a field int id = 0; while (results.next()) { id = results.getInt(1); } PreparedStatement addUserToGroup = connection .prepareStatement("insert into GroupTable (userID, email) values (?, ?)"); addUserToGroup.setInt(1, id); addUserToGroup.setString(2, email); addUserToGroup.executeUpdate(); PreparedStatement addMajor = connection .prepareStatement("insert into MajorCodes (userID, majorCode) values (?, ?)"); addMajor.setInt(1, id); addMajor.setString(2, major); addMajor.executeUpdate(); sendEmails send = new sendEmails(); send.sendConfirmation(email, firstName, lastName, randomNum, id); System.out.print("test"); } finally { connection.close(); } return "thanks"; }
From source file:net.mindengine.oculus.frontend.service.runs.JdbcTestRunDAO.java
@Override public Long createTestRunParameter(Long testRunId, String name, String value, boolean isInput) throws Exception { PreparedStatement ps = getConnection().prepareStatement( "insert into test_run_parameters (test_run_id, name, value, type) values (?,?,?,?)"); ps.setLong(1, testRunId);/* w ww. ja v a 2 s. c om*/ ps.setString(2, name); ps.setString(3, value); if (isInput) { ps.setString(4, "input"); } else ps.setString(4, "output"); logger.info(ps); ps.execute(); ResultSet rs = ps.getGeneratedKeys(); if (rs.next()) { return rs.getLong(1); } return null; }