Example usage for java.sql Statement RETURN_GENERATED_KEYS

List of usage examples for java.sql Statement RETURN_GENERATED_KEYS

Introduction

In this page you can find the example usage for java.sql Statement RETURN_GENERATED_KEYS.

Prototype

int RETURN_GENERATED_KEYS

To view the source code for java.sql Statement RETURN_GENERATED_KEYS.

Click Source Link

Document

The constant indicating that generated keys should be made available for retrieval.

Usage

From source file:com.xqdev.sql.MLSQL.java

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/xml");

    Namespace sql = Namespace.getNamespace("sql", "http://xqdev.com/sql");
    Document responseDoc = new Document();
    Element root = new Element("result", sql);
    Element meta = new Element("meta", sql);
    responseDoc.setRootElement(root);//www . j a  va 2 s. co m
    root.addContent(meta);

    Document requestDoc = null;
    try {
        // Normally the request comes via the post body,
        // but we let you bookmark w/ a query string
        String postbody = req.getParameter("postbody");
        if (postbody != null) {
            SAXBuilder builder = new SAXBuilder();
            requestDoc = builder.build(new StringReader(postbody));
        } else {
            InputStream in = req.getInputStream();
            SAXBuilder builder = new SAXBuilder();
            requestDoc = builder.build(in);
        }
    } catch (Exception e) {
        addExceptions(meta, e);
        // Now write the error and return
        OutputStream out = res.getOutputStream();
        new XMLOutputter().output(responseDoc, out);
        out.flush();
        return;
    }

    Connection con = null;
    try {
        Namespace[] namespaces = new Namespace[] { sql };
        XPathHelper xpath = new XPathHelper(requestDoc, namespaces);

        String type = xpath.getString("/sql:request/sql:type");
        String query = xpath.getString("/sql:request/sql:query");
        int maxRows = xpath.getInt("/sql:request/sql:execute-options/sql:max-rows", -1);
        int queryTimeout = xpath.getInt("/sql:request/sql:execute-options/sql:query-timeout", -1);
        int maxFieldSize = xpath.getInt("/sql:request/sql:execute-options/sql:max-field-size", -1);
        List<Element> params = xpath
                .getElements("/sql:request/sql:execute-options/sql:parameters/sql:parameter");

        con = pool.getConnection();

        PreparedStatement stmt = null;

        if (type.equalsIgnoreCase("procedure")) {
            stmt = con.prepareCall(query);
        } else {
            // Note this call depends on JDBC 3.0 (accompanying Java 1.4).
            // The call without the 2nd argument would work on earlier JVMs,
            // you just won't catch any generated keys.
            stmt = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        }
        configureStatement(stmt, maxRows, queryTimeout, maxFieldSize);
        parameterizeStatement(stmt, params);

        if (type.equalsIgnoreCase("select")) {
            try {
                ResultSet rs = stmt.executeQuery();
                addWarnings(meta, stmt.getWarnings());
                addResultSet(root, rs);
            } catch (SQLException e) {
                addExceptions(meta, e);
                Log.log(e);
            }
        } else if (type.equalsIgnoreCase("update")) {
            try {
                int count = stmt.executeUpdate();
                addWarnings(meta, stmt.getWarnings());
                addUpdateCount(meta, count);
                try {
                    addGeneratedKeys(meta, stmt.getGeneratedKeys());
                } catch (SQLException e) {
                    // Generated keys are available on INSERT calls but not UPDATE calls
                    // So catch and eat the exception that Oracle (and maybe others) will throw
                }
            } catch (SQLException e) {
                addExceptions(meta, e);
            }
        } else if (type.equalsIgnoreCase("procedure")) {
            boolean isResultSet = stmt.execute();
            if (isResultSet) {
                addResultSet(root, stmt.getResultSet());
                addOutParam(root, stmt, params);
            } else {
                addOutParam(root, stmt, params);
            }
        } else {
            try {
                boolean isResultSet = stmt.execute();
                addWarnings(meta, stmt.getWarnings());
                if (isResultSet) {
                    addResultSet(root, stmt.getResultSet());
                } else {
                    addUpdateCount(meta, stmt.getUpdateCount());
                    addGeneratedKeys(meta, stmt.getGeneratedKeys());
                }
            } catch (SQLException e) {
                addExceptions(meta, e);
            }
        }
        // Close the statement holding the connection to the JDBC Server
        stmt.close();
    } catch (Exception e) {
        addExceptions(meta, e);
    } finally {
        if (con != null)
            pool.returnConnection(con);
    }

    OutputStream out = res.getOutputStream();
    new XMLOutputter().output(responseDoc, out);
    out.flush();
}

From source file:org.kawanfw.test.api.client.autogeneratedkeys.InsertStatementTestAutoKeysTest.java

/**
 * Do a 100 row insert inside a loop//  w ww  .java  2  s.c  om
 * 
 * @param connection
 *            the AceQL Connection
 * 
 * @param numberToInsert
 *            the number for instances to insert
 * 
 * @param useRawExecute
 *            if true, we will insert using execute()
 * 
 * @throws Exception
 *             it any Exception occurs
 */
public static void insertStatement(Connection connection, int numberToInsert, boolean useRawExecute,
        boolean autoCommitOn) throws Exception {

    long maxCustomerId = getMaxCustomerId(connection);
    MessageDisplayer.display("maxCustomerId: " + maxCustomerId);

    // We can now use our Remote JDBC Connection as a regular Connection!
    if (!autoCommitOn) {
        connection.setAutoCommit(false);
    }

    // We will do all our remote insert in a SQL Transaction
    try {

        Statement statement = null;

        String title;
        String fname;
        String lname;
        String addressline;
        String town;
        String zipcode;
        String phone;

        MessageDisplayer.display("");
        MessageDisplayer.display("Inserting " + numberToInsert + " customers...");

        statement = connection.createStatement();

        // //SystemOutHandle.display("customer_id: " + customerId);

        title = "Sir";

        fname = "Smith_" + numberToInsert;
        lname = "Smith_" + numberToInsert;

        addressline = numberToInsert + ", Csar Avenue";
        town = "JavaLand_" + numberToInsert;
        zipcode = numberToInsert + "45";
        phone = numberToInsert + "-12345678";

        String sql = "insert into customer_auto (customer_title, fname, lname, addressline, town, zipcode, phone) "
                + " values ( '?2', '?3', '?4', '?5', '?6', '?7', '?8' )";

        sql = sql.replace("?2", title);
        sql = sql.replace("?3", fname);
        sql = sql.replace("?4", lname);
        sql = sql.replace("?5", addressline);
        sql = sql.replace("?6", town);
        sql = sql.replace("?7", zipcode);
        sql = sql.replace("?8", phone);

        if (useRawExecute) {
            statement.execute(sql, Statement.RETURN_GENERATED_KEYS);
        } else {
            statement.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
        }

        // We do either everything in a single transaction or nothing
        if (!autoCommitOn) {
            connection.commit(); // Commit is propagated on Server
        }

        ResultSet keys = statement.getGeneratedKeys();
        long lastKey = -1;
        while (keys.next()) {
            lastKey = keys.getLong(1);
        }
        keys.close();

        MessageDisplayer.display("Last Key: " + lastKey);

        // Don't know why: there is a bug in some engines where sometime
        // increment is > 1
        // Assert.assertEquals("last key = maxCustomerId + 1", lastKey,
        // maxCustomerId + 1);

        // So do another test:
        Assert.assertEquals("last key >= 1", true, lastKey > 1);

        statement.close();

    } catch (Exception e) {
        if (!autoCommitOn) {
            connection.rollback();
        }
        throw e;
    } finally {
        if (!autoCommitOn) {
            connection.setAutoCommit(true);
        }
    }

}

From source file:com.wso2telco.dep.ratecardservice.dao.RateDefinitionDAO.java

public RateDefinitionDTO addRateDefinition(RateDefinitionDTO rateDefinition) throws BusinessException {

    Connection con = null;/*from w  w  w.  j a v  a  2 s .  c  om*/
    PreparedStatement ps = null;
    ResultSet rs = null;
    Integer rateDefId = 0;

    try {

        con = DbUtils.getDbConnection(DataSourceNames.WSO2TELCO_RATE_DB);
        if (con == null) {

            log.error("unable to open " + DataSourceNames.WSO2TELCO_RATE_DB + " database connection");
            throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
        }

        StringBuilder query = new StringBuilder("insert into ");
        query.append(DatabaseTables.RATE_DEF.getTObject());
        query.append(
                " (rate_defname, rate_defdesc, rate_defdefault, currencyid, rate_typeid, rate_defcategorybase, tariffid, createdby)");
        query.append(" values");
        query.append(" (?, ?, ?, ?, ?, ?, ?, ?)");

        ps = con.prepareStatement(query.toString(), Statement.RETURN_GENERATED_KEYS);

        log.debug("sql query in addRateDefinition : " + ps);

        ps.setString(1, rateDefinition.getRateDefName());
        ps.setString(2, rateDefinition.getRateDefDescription());
        ps.setInt(3, rateDefinition.getRateDefDefault());
        ps.setInt(4, rateDefinition.getCurrency().getCurrencyId());
        ps.setInt(5, rateDefinition.getRateType().getRateTypeId());
        ps.setInt(6, rateDefinition.getRateDefCategoryBase());
        ps.setInt(7, rateDefinition.getTariff().getTariffId());
        ps.setString(8, rateDefinition.getCreatedBy());

        ps.executeUpdate();

        rs = ps.getGeneratedKeys();

        while (rs.next()) {

            rateDefId = rs.getInt(1);
        }

        rateDefinition.setRateDefId(rateDefId);
    } catch (SQLException e) {

        log.error("database operation error in addRateDefinition : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } catch (Exception e) {

        log.error("error in addRateDefinition : ", e);
        throw new BusinessException(ServiceError.SERVICE_ERROR_OCCURED);
    } finally {

        DbUtils.closeAllConnections(ps, con, rs);
    }

    return rateDefinition;
}

From source file:net.bhira.sample.api.dao.DepartmentDaoImpl.java

/**
 * @see net.bhira.sample.api.dao.DepartmentDao#save(net.bhira.sample.model.Department)
 *///from  w w w .  j a v a 2  s .com
@Override
public void save(Department department) throws ObjectNotFoundException, DuplicateNameException,
        InvalidObjectException, InvalidReferenceException {
    try {
        if (department == null) {
            throw new InvalidObjectException("Department object is null.");
        }

        department.initForSave();
        department.validate();
        boolean isNew = department.isNew();
        int count = 0;

        if (isNew) {
            // for new department, construct SQL insert statement
            KeyHolder keyHolder = new GeneratedKeyHolder();
            count = jdbcTemplate.update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement pstmt = connection.prepareStatement(SQL_INSERT,
                            Statement.RETURN_GENERATED_KEYS);
                    pstmt.setLong(1, department.getCompanyId());
                    pstmt.setString(2, department.getName());
                    pstmt.setString(3, department.getBillingAddress());
                    pstmt.setString(4, department.getShippingAddress());
                    pstmt.setTimestamp(5, new Timestamp(department.getCreated().getTime()));
                    pstmt.setTimestamp(6, new Timestamp(department.getModified().getTime()));
                    pstmt.setString(7, department.getCreatedBy());
                    pstmt.setString(8, department.getModifiedBy());
                    return pstmt;
                }
            }, keyHolder);

            // fetch the newly created auto-increment ID
            department.setId(keyHolder.getKey().longValue());
            LOG.debug("inserted department, count = {}, id = {}", count, department.getId());

        } else {
            // for existing department, construct SQL update statement
            Object[] args = new Object[] { department.getCompanyId(), department.getName(),
                    department.getBillingAddress(), department.getShippingAddress(), department.getModified(),
                    department.getModifiedBy(), department.getId() };
            count = jdbcTemplate.update(SQL_UPDATE, args);
            LOG.debug("updated department, count = {}, id = {}", count, department.getId());
        }

        // if insert/update has 0 count value, then rollback
        if (count <= 0) {
            throw new ObjectNotFoundException("Department with ID " + department.getId() + " was not found.");
        }

        // update dependent entries, as needed
        if (isNew) {

            // for new model if there is contact info, save it to contact info table and then
            // add entry in relationship table
            if (department.getContactInfo() != null) {
                contactInfoDao.save(department.getContactInfo());
                Object[] args = new Object[] { department.getId(), department.getContactInfo().getId() };
                jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
            }

        } else {
            // for existing model, fetch contact info ID from relationship table
            List<Long> cinfoIds = jdbcTemplate.queryForList(SQL_CINFO_REL_LOAD, Long.class,
                    new Object[] { department.getId() });
            Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null;

            if (department.getContactInfo() == null) {
                // clean up old contact info entry, if needed
                if (cinfoId != null) {
                    jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { department.getId() });
                    contactInfoDao.delete(cinfoId);
                }

            } else {
                // insert/update contact info entry
                if (cinfoId != null) {
                    department.getContactInfo().setId(cinfoId);
                    contactInfoDao.save(department.getContactInfo());
                } else {
                    contactInfoDao.save(department.getContactInfo());
                    Object[] args = new Object[] { department.getId(), department.getContactInfo().getId() };
                    jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
                }
            }
        }

    } catch (DataIntegrityViolationException dive) {
        String msg = dive.getMessage();
        if (msg != null) {
            if (msg.contains("uq_department")) {
                throw new DuplicateNameException("Duplicate department name " + department.getName(), dive);
            } else if (msg.contains("fk_department_compy")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'companyId'", dive);
            }
        }
        throw dive;
    }
}

From source file:org.wso2.intcloud.core.dao.ApplicationDAO.java

/**
 * Method for adding version details to database.
 *
 * @param dbConnection database connection
 * @param version version object/*from  ww w  . j  a  v a 2s. c  om*/
 * @param applicationId application id
 * @param tenantId tenant id
 * @return
 * @throws IntCloudException
 */
public void addVersion(Connection dbConnection, Version version, int applicationId, int tenantId)
        throws IntCloudException {

    PreparedStatement preparedStatement = null;
    int versionId = 0;
    ResultSet resultSet = null;

    try {

        preparedStatement = dbConnection.prepareStatement(SQLQueryConstants.ADD_VERSION,
                Statement.RETURN_GENERATED_KEYS);
        preparedStatement.setString(1, version.getVersionName());
        preparedStatement.setString(2, version.getHashId());
        preparedStatement.setInt(3, applicationId);
        preparedStatement.setInt(4, version.getRuntimeId());
        preparedStatement.setInt(5, tenantId);

        preparedStatement.execute();

        resultSet = preparedStatement.getGeneratedKeys();
        while (resultSet.next()) {
            versionId = resultSet.getInt(1);
        }

        //            List<Tag> tags = version.getTags();
        //            if (tags != null) {
        //                addTags(dbConnection, tags, version.getHashId(), tenantId);
        //            }
        //
        //            List<RuntimeProperty> runtimeProperties = version.getRuntimeProperties();
        //            if (runtimeProperties != null) {
        //                addRunTimeProperties(dbConnection, runtimeProperties, version.getHashId(), tenantId);
        //            }

    } catch (SQLException e) {
        String msg = "Error occurred while adding application version to database for application id : "
                + applicationId + " version : " + version.getVersionName() + " in tenant : " + tenantId;
        log.error(msg, e);
        throw new IntCloudException(msg, e);
    } finally {
        DBUtil.closeResultSet(resultSet);
        DBUtil.closePreparedStatement(preparedStatement);
    }

}

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  va 2s. c  o 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.bhira.sample.api.dao.EmployeeDaoImpl.java

/**
 * @see net.bhira.sample.api.dao.EmployeeDao#save(net.bhira.sample.model.Employee)
 *///www  .  j a  v a  2  s.  c  om
@Override
public void save(Employee employee)
        throws ObjectNotFoundException, InvalidObjectException, InvalidReferenceException {
    try {
        if (employee == null) {
            throw new InvalidObjectException("Employee object is null.");
        }

        employee.initForSave();
        employee.validate();
        boolean isNew = employee.isNew();
        int count = 0;

        if (isNew) {
            // for new employee, construct SQL insert statement
            KeyHolder keyHolder = new GeneratedKeyHolder();
            count = jdbcTemplate.update(new PreparedStatementCreator() {
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement pstmt = connection.prepareStatement(SQL_INSERT,
                            Statement.RETURN_GENERATED_KEYS);
                    pstmt.setLong(1, employee.getCompanyId());
                    if (employee.getDepartmentId() == 0) {
                        pstmt.setNull(2, java.sql.Types.BIGINT);
                    } else {
                        pstmt.setLong(2, employee.getDepartmentId());
                    }
                    pstmt.setString(3, employee.getName());
                    if (employee.getManagerId() == 0) {
                        pstmt.setNull(4, java.sql.Types.BIGINT);
                    } else {
                        pstmt.setLong(4, employee.getManagerId());
                    }
                    pstmt.setString(5, employee.getSalutation());
                    pstmt.setString(6, employee.getSex() == null ? null : employee.getSex().toString());
                    pstmt.setDate(7, employee.getDOB() == null ? null : new Date(employee.getDOB().getTime()));
                    pstmt.setString(8, employee.getTitle());
                    pstmt.setString(9, employee.getAddress());
                    pstmt.setTimestamp(10, new Timestamp(employee.getCreated().getTime()));
                    pstmt.setTimestamp(11, new Timestamp(employee.getModified().getTime()));
                    pstmt.setString(12, employee.getCreatedBy());
                    pstmt.setString(13, employee.getModifiedBy());
                    return pstmt;
                }
            }, keyHolder);

            // fetch the newly created auto-increment ID
            employee.setId(keyHolder.getKey().longValue());
            LOG.debug("inserted employee, count = {}, id = {}", count, employee.getId());

        } else {
            // for existing employee, construct SQL update statement
            Long deptId = employee.getDepartmentId() == 0 ? null : employee.getDepartmentId();
            Long mgrId = employee.getManagerId() == 0 ? null : employee.getManagerId();
            String sex = employee.getSex() == null ? null : employee.getSex().toString();
            Date dob = employee.getDOB() == null ? null : new Date(employee.getDOB().getTime());
            Object[] args = new Object[] { employee.getCompanyId(), deptId, employee.getName(), mgrId,
                    employee.getSalutation(), sex, dob, employee.getTitle(), employee.getAddress(),
                    employee.getModified(), employee.getModifiedBy(), employee.getId() };
            count = jdbcTemplate.update(SQL_UPDATE, args);
            LOG.debug("updated employee, count = {}, id = {}", count, employee.getId());
        }

        // if insert/update has 0 count value, then rollback
        if (count <= 0) {
            throw new ObjectNotFoundException("Employee with ID " + employee.getId() + " was not found.");
        }

        // update dependent entries, as needed
        if (isNew) {

            // for new model if there is contact info, save it to contact info table and then
            // add entry in relationship table
            if (employee.getContactInfo() != null) {
                contactInfoDao.save(employee.getContactInfo());
                Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() };
                jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
            }

        } else {
            // for existing model, fetch contact info ID from relationship table
            List<Long> cinfoIds = jdbcTemplate.queryForList(SQL_CINFO_REL_LOAD, Long.class,
                    new Object[] { employee.getId() });
            Long cinfoId = (cinfoIds != null && !cinfoIds.isEmpty()) ? cinfoIds.get(0) : null;

            if (employee.getContactInfo() == null) {
                // clean up old contact info entry, if needed
                if (cinfoId != null) {
                    jdbcTemplate.update(SQL_CINFO_REL_DELETE, new Object[] { employee.getId() });
                    contactInfoDao.delete(cinfoId);
                }

            } else {
                // insert/update contact info entry
                if (cinfoId != null) {
                    employee.getContactInfo().setId(cinfoId);
                    contactInfoDao.save(employee.getContactInfo());
                } else {
                    contactInfoDao.save(employee.getContactInfo());
                    Object[] args = new Object[] { employee.getId(), employee.getContactInfo().getId() };
                    jdbcTemplate.update(SQL_CINFO_REL_INSERT, args);
                }
            }
        }

    } catch (DataIntegrityViolationException dive) {
        String msg = dive.getMessage();
        if (msg != null) {
            if (msg.contains("fk_employee_compy")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'companyId'", dive);
            } else if (msg.contains("fk_employee_dept")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'departmentId'", dive);
            } else if (msg.contains("fk_employee_mgr")) {
                throw new InvalidReferenceException("Invalid reference for attribute 'managerId'", dive);
            }
        }
        throw dive;
    }
}

From source file:code.Servlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request/*from w  ww.ja va 2s . com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String start_date, end_date;

    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();

        conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement();
        String sql = "SELECT * FROM Event where now() < date_start";
        ResultSet res = stmt.executeQuery(sql);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
        Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        // Open a connection                    
        //    conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
        //  stmt = conn.createStatement();
        if (request.getParameter("city") != null) {
            //add event
            //2016-01-01 00:00:00
            start_date = request.getParameter("start_data").substring(6, 10) + "-"
                    + request.getParameter("start_data").substring(0, 2) + "-"
                    + request.getParameter("start_data").substring(3, 5) + ' ';
            start_date += request.getParameter("start_hour").substring(0, 5) + ":00";
            end_date = request.getParameter("end_data").substring(6, 10) + "-"
                    + request.getParameter("end_data").substring(0, 2) + "-"
                    + request.getParameter("end_data").substring(3, 5) + ' ';
            end_date += request.getParameter("end_hour").substring(0, 5) + ":00";

            String sql = "INSERT INTO `mydb_treasure`.`Event`(`date_start`, `date_end`, `name_event`,  `City_name`, `number_step`) VALUES ('"
                    + start_date + "', '" + end_date + "', '" + request.getParameter("name_event") + "', '"
                    + request.getParameter("city") + "', '" + request.getParameter("number_step") + "')";
            stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            ResultSet newIdEvent = stmt.getGeneratedKeys();
            String IdEvent;
            if (newIdEvent.next()) {
                IdEvent = newIdEvent.getString(1);
                System.out.println(IdEvent);
                //Timer t = new Timer();
                //t.schedule(new StartEvent(IdEvent), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(start_date));
                out.println("<!DOCTYPE html>");
                out.println("<html>");
                out.println(
                        "<head> <meta http-equiv='refresh' content='3; url=http://localhost:8080/Treasure_server/' >");
                out.println("</head>");
                out.println("<body>");
                out.println("Event added!!");
                out.println("</body>");
                out.println("</html>");
            }
        }
    } catch (SQLException ex) {
        Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
    }
    /*catch (ParseException ex) {
    Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex);
    }*/
}

From source file:net.solarnetwork.node.dao.jdbc.AbstractJdbcDao.java

/**
 * Store (insert) a new domain object./*from  w  ww  . ja  v  a2s  . c om*/
 * 
 * <p>
 * If {@link #isUseAutogeneratedKeys()} is <em>true</em> then this method
 * will use JDBC's {@link Statement#RETURN_GENERATED_KEYS} to obtain the
 * auto-generated primary key for the newly inserted object. Otherwise, this
 * method will call the
 * {@link #storeDomainObjectWithoutAutogeneratedKeys(T, String)} method.
 * </p>
 * 
 * @param obj
 *        the domain object to persist
 * @param sqlInsert
 *        the SQL to persist the object with
 * @return the primary key created for the domain object
 */
protected Long storeDomainObject(final T obj, final String sqlInsert) {
    if (!useAutogeneratedKeys) {
        return storeDomainObjectWithoutAutogeneratedKeys(obj, sqlInsert);
    }
    GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
    getJdbcTemplate().update(new PreparedStatementCreator() {

        @Override
        public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
            PreparedStatement ps = con.prepareStatement(sqlInsert, Statement.RETURN_GENERATED_KEYS);
            setStoreStatementValues(obj, ps);
            return ps;
        }
    }, keyHolder);
    if (keyHolder.getKey() != null) {
        return Long.valueOf(keyHolder.getKey().longValue());
    }
    return null;
}

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheHelpers.java

/**
 * Method to create a new entry in the file table in the database.
 * The file_id is automatically created by the database, and the argument
 * is used for the filename for this new entry to the table.
 * This will also create a replicafileinfo entry for each replica.
 *
 * @param filename The filename for the new entry in the file table.
 * @param connection An open connection to the archive database
 * @throws IllegalState If the file cannot be inserted into the database.
 * @return created file_id for the new entry.
 *//*from w w  w  . j a v a  2s .  c om*/
protected static long insertFileIntoDB(String filename, Connection connection) throws IllegalState {
    log.debug("Insert file '" + filename + "' into database");
    PreparedStatement statement = null;
    try {

        // Make the SQL statement for putting the replica into the database
        // and insert the variables for the entry to the replica table.
        statement = connection.prepareStatement("INSERT INTO file (filename) " + "VALUES ( ? )",
                Statement.RETURN_GENERATED_KEYS);
        statement.setString(1, filename);

        // execute the SQL statement
        statement.executeUpdate();
        // Retrieve the fileId for the just inserted file.
        ResultSet resultset = statement.getGeneratedKeys();
        resultset.next();
        long fileId = resultset.getLong(1);
        connection.commit();

        // Create replicafileinfo for each replica.
        createReplicaFileInfoEntriesInDB(fileId, connection);
        log.debug("Insert file '" + filename + "' into database completed. Assigned fileID=" + fileId);
        return fileId;
    } catch (SQLException e) {
        throw new IllegalState("Cannot add file '" + filename + "' to the database.", e);
    } finally {
        DBUtils.closeStatementIfOpen(statement);
    }
}