List of usage examples for java.sql PreparedStatement setDate
void setDate(int parameterIndex, java.sql.Date x) throws SQLException;
java.sql.Date
value using the default time zone of the virtual machine that is running the application. From source file:org.apache.phoenix.end2end.index.IndexExpressionIT.java
protected void helpTestCreateAndUpdate(boolean mutable, boolean localIndex) throws Exception { String dataTableName = mutable ? MUTABLE_INDEX_DATA_TABLE : INDEX_DATA_TABLE; String fullDataTableName = INDEX_DATA_SCHEMA + QueryConstants.NAME_SEPARATOR + dataTableName; Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); Connection conn = DriverManager.getConnection(getUrl(), props); try {/*from w ww . j ava 2s . c om*/ conn.setAutoCommit(false); populateDataTable(conn, dataTableName); // create an expression index String ddl = "CREATE " + (localIndex ? "LOCAL" : "") + " INDEX IDX ON " + fullDataTableName + " ((UPPER(varchar_pk) || '_' || UPPER(char_pk) || '_' || UPPER(varchar_col1) || '_' || UPPER(b.char_col2))," + " (decimal_pk+int_pk+decimal_col2+int_col1)," + " date_pk+1, date1+1, date2+1 )" + " INCLUDE (long_col1, long_col2)"; PreparedStatement stmt = conn.prepareStatement(ddl); stmt.execute(); // run select query with expression in WHERE clause String whereSql = "SELECT long_col1, long_col2 from " + fullDataTableName + " WHERE UPPER(varchar_pk) || '_' || UPPER(char_pk) || '_' || UPPER(varchar_col1) || '_' || UPPER(b.char_col2) = ?" + " AND decimal_pk+int_pk+decimal_col2+int_col1=?" // since a.date1 and b.date2 are NULLABLE and date is fixed width, these expressions are stored as // DECIMAL in the index (which is not fixed width) + " AND date_pk+1=? AND date1+1=? AND date2+1=?"; stmt = conn.prepareStatement(whereSql); stmt.setString(1, "VARCHAR1_CHAR1 _A.VARCHAR1_B.CHAR1 "); stmt.setInt(2, 3); Date date = DateUtil.parseDate("2015-01-02 00:00:00"); stmt.setDate(3, date); stmt.setDate(4, date); stmt.setDate(5, date); // verify that the query does a range scan on the index table ResultSet rs = stmt.executeQuery("EXPLAIN " + whereSql); assertEquals(localIndex ? "CLIENT PARALLEL 1-WAY RANGE SCAN OVER _LOCAL_IDX_INDEX_TEST." + dataTableName + " [-32768,'VARCHAR1_CHAR1 _A.VARCHAR1_B.CHAR1 ',3,'2015-01-02 00:00:00.000',1,420,156,800,000,1,420,156,800,000]\nCLIENT MERGE SORT" : "CLIENT PARALLEL 1-WAY RANGE SCAN OVER INDEX_TEST.IDX ['VARCHAR1_CHAR1 _A.VARCHAR1_B.CHAR1 ',3,'2015-01-02 00:00:00.000',1,420,156,800,000,1,420,156,800,000]", QueryUtil.getExplainPlan(rs)); // verify that the correct results are returned rs = stmt.executeQuery(); assertTrue(rs.next()); assertEquals(1, rs.getInt(1)); assertEquals(1, rs.getInt(2)); assertFalse(rs.next()); // verify all rows in data table are present in index table String indexSelectSql = "SELECT UPPER(varchar_pk) || '_' || UPPER(char_pk) || '_' || UPPER(varchar_col1) || '_' || UPPER(b.char_col2), " + "decimal_pk+int_pk+decimal_col2+int_col1, " + "date_pk+1, date1+1, date2+1, " + "varchar_pk, char_pk, int_pk, long_pk, decimal_pk, " + "long_col1, long_col2 " + "from " + fullDataTableName; rs = conn.createStatement().executeQuery("EXPLAIN " + indexSelectSql); assertEquals(localIndex ? "CLIENT PARALLEL 1-WAY RANGE SCAN OVER _LOCAL_IDX_" + fullDataTableName + " [-32768]\nCLIENT MERGE SORT" : "CLIENT PARALLEL 1-WAY FULL SCAN OVER INDEX_TEST.IDX", QueryUtil.getExplainPlan(rs)); rs = conn.createStatement().executeQuery(indexSelectSql); verifyResult(rs, 1); verifyResult(rs, 2); // Insert two more rows to the index data table String upsert = "UPSERT INTO " + fullDataTableName + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; stmt = conn.prepareStatement(upsert); insertRow(stmt, 3); insertRow(stmt, 4); conn.commit(); rs = conn.createStatement().executeQuery(indexSelectSql); verifyResult(rs, 1); verifyResult(rs, 2); // verify that two rows added after index was created were also added to // the index table verifyResult(rs, 3); verifyResult(rs, 4); conn.createStatement().execute("DROP INDEX IDX ON " + fullDataTableName); } finally { conn.close(); } }
From source file:org.apache.hive.jdbc.TestJdbcDriver2.java
@Test public void testPrepareSetDate() throws Exception { try {/*from w ww . ja v a 2s . c o m*/ String sql = "select * from " + dataTypeTableName + " where c20 = ?"; PreparedStatement ps = con.prepareStatement(sql); java.sql.Date dtValue = java.sql.Date.valueOf("2013-01-01"); ps.setDate(1, dtValue); ResultSet res = ps.executeQuery(); assertTrue(res.next()); assertEquals("2013-01-01", res.getString(20)); ps.close(); } catch (Exception e) { e.printStackTrace(); fail(e.toString()); } }
From source file:com.novartis.opensource.yada.util.QueryUtils.java
/** * Calls the appropriate setter method for {@code type} in the {@code pstmt}, * performing the appropriate type conversion or syntax change as needed * (e.g., for {@link java.sql.Date}s)//from ww w . ja va 2 s .co m * * @param pstmt * the statement to which to assign the parameter values * @param index * the position of the parameter * @param type * the data type of the parameter * @param val * the value to assign */ @SuppressWarnings("static-method") private void setQueryParameter(PreparedStatement pstmt, int index, char type, String val) { String idx = (index < 10) ? " " + String.valueOf(index) : String.valueOf(index); l.debug("Setting param [" + idx + "] of type [" + String.valueOf(type) + "] to: " + val); try { switch (type) { case DATE: try { if ("".equals(val) || val == null) { pstmt.setNull(index, java.sql.Types.DATE); } else { SimpleDateFormat sdf = new SimpleDateFormat(STANDARD_DATE_FMT); ParsePosition pp = new ParsePosition(0); Date dateVal = sdf.parse(val, pp); if (dateVal == null) { sdf = new SimpleDateFormat(ORACLE_DATE_FMT); dateVal = sdf.parse(val, pp); } if (dateVal != null) { long t = dateVal.getTime(); java.sql.Date sqlDateVal = new java.sql.Date(t); pstmt.setDate(index, sqlDateVal); } } } catch (Exception e) { l.error("Error: " + e.getMessage()); } break; case INTEGER: try { int ival = Integer.parseInt(val); pstmt.setInt(index, ival); } catch (NumberFormatException nfe) { l.error("Error: " + nfe.getMessage()); l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type) + "] to: null"); pstmt.setNull(index, java.sql.Types.INTEGER); } catch (NullPointerException npe) { l.error("Error: " + npe.getMessage()); l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type) + "] to: null"); pstmt.setNull(index, java.sql.Types.INTEGER); } catch (Exception sqle) { l.error("Error: " + sqle.getMessage()); l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type) + "] to: 0"); pstmt.setNull(index, java.sql.Types.INTEGER); } break; case NUMBER: try { float fval = Float.parseFloat(val); pstmt.setFloat(index, fval); } catch (NumberFormatException nfe) { l.error("Error: " + nfe.getMessage()); l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type) + "] to: null"); pstmt.setNull(index, java.sql.Types.INTEGER); } catch (NullPointerException npe) { l.error("Error: " + npe.getMessage()); l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type) + "] to: null"); pstmt.setNull(index, java.sql.Types.INTEGER); } catch (Exception sqle) { l.error("Error: " + sqle.getMessage()); l.debug("Setting param [" + String.valueOf(index) + "] of type [" + String.valueOf(type) + "] to: null"); pstmt.setNull(index, java.sql.Types.INTEGER); } break; case OUTPARAM_DATE: ((CallableStatement) pstmt).registerOutParameter(index, java.sql.Types.DATE); break; case OUTPARAM_INTEGER: ((CallableStatement) pstmt).registerOutParameter(index, java.sql.Types.INTEGER); break; case OUTPARAM_NUMBER: ((CallableStatement) pstmt).registerOutParameter(index, java.sql.Types.FLOAT); break; case OUTPARAM_VARCHAR: ((CallableStatement) pstmt).registerOutParameter(index, java.sql.Types.VARCHAR); break; default: // VARCHAR2 pstmt.setString(index, val); break; } } catch (SQLException e) { e.printStackTrace(); l.error(e.getMessage()); } }
From source file:migration.ProjektMigration.java
/** * Creates the exemplar.//from ww w. j av a 2 s. c o m * * @param con * the con */ public void createExemplar(final Connection con) { String load_sql; Statement load_stmt; ResultSet load_rs; String store_sql; PreparedStatement store_prepstmt; final ResultSet store_rs; try { load_sql = "select Besteller, Exemplar, Sigel, Titelnummer AS Journal, Lieferant, Printan, Beteiligung, Form, Zugangsart, " + "Status, Bestellnummer, Kundennummer, AboNummer, Privatabo, ExKommentar, PrintexBayern, " + "AbbestZum, Abbestellung, UmbestZum, Umbestellung from Exemplartabelle "; load_stmt = this.leg_con.createStatement(); store_sql = "insert into exemplar (abbestZum, abbestellung, abonummer, bestellnummer, beteiligung, " + "exKommentar, form, kundennummer, printexBayern, privatabo, status, umbestZum, umbestellung, zugangsart, " + "besteller_sigelId, eigentuemer_sigelId, journal_id, lieferant_id, zustaendigeBib_sigelId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; store_prepstmt = this.tgt_con.prepareStatement(store_sql); // evtl. // brauchen // wir // was // in // Richtung: // Statement.RETURN_GENERATED_KEYS final int laenge = this.help.sqlGetLength(con, load_sql); this.exemplare = new int[laenge]; // logger.info("Lese von Besteller"); load_stmt.execute(load_sql); load_rs = load_stmt.getResultSet(); // logger.info("Schreibe nach Besteller"); for (int i = 0; i < laenge; i++) { // System.err.println("geht doch!"); load_rs.next(); this.exemplare[i] = load_rs.getInt("Exemplar"); store_prepstmt.setDate(1, load_rs.getDate("AbbestZum")); store_prepstmt.setString(2, load_rs.getString("Abbestellung")); store_prepstmt.setString(3, load_rs.getString("AboNummer")); store_prepstmt.setString(4, load_rs.getString("Bestellnummer")); store_prepstmt.setString(5, load_rs.getString("Beteiligung")); store_prepstmt.setString(6, load_rs.getString("exKommentar")); store_prepstmt.setString(7, load_rs.getString("Form")); store_prepstmt.setString(8, load_rs.getString("Kundennummer")); store_prepstmt.setString(9, load_rs.getString("PrintexBayern")); store_prepstmt.setBoolean(10, load_rs.getBoolean("privatabo")); store_prepstmt.setString(11, load_rs.getString("Status")); store_prepstmt.setDate(12, load_rs.getDate("UmbestZum")); store_prepstmt.setString(13, load_rs.getString("Umbestellung")); store_prepstmt.setString(14, load_rs.getString("Zugangsart")); final String besteller = load_rs.getString("Besteller"); final int bestellerID_neu = this.help.getIdFromStringArray(this.bestellers, besteller); int sigelID = 0; if (bestellerID_neu != 0) { sigelID = this.bestellers_sigels[bestellerID_neu - 1]; } if (sigelID != 0) { store_prepstmt.setLong(15, sigelID); } else { store_prepstmt.setNull(15, java.sql.Types.BIGINT); } final String print = load_rs.getString("Printan"); // System.err.println("print: "+print+" getID: "+help.getIdFromStringArray(help.getSigel(), // print)); if (this.help.getIdFromStringArray(this.help.getSigel(), print) != 0) { store_prepstmt.setLong(16, (this.help.getIdFromStringArray(this.help.getSigel(), print))); } else { store_prepstmt.setNull(16, java.sql.Types.BIGINT); } final int j = load_rs.getInt("Journal"); // System.err.println("journal: "+j+" getID: "+help.getIdFromIntArray(help.getJournals(), // j)); if (this.help.getIdFromIntArray(this.help.getJournals(), j) != 0) { store_prepstmt.setLong(17, this.help.getIdFromIntArray(this.help.getJournals(), j)); } else { store_prepstmt.setNull(17, java.sql.Types.BIGINT); } final String lief = load_rs.getString("Lieferant"); // System.err.println("lieferant: "+ lief + // " ist "+help.getIdFromStringArray(help.getInstitutionen(), // lief)); if (this.help.getIdFromStringArray(this.help.getInstitutionen(), lief) != 0) { store_prepstmt.setLong(18, this.help.getIdFromStringArray(this.help.getInstitutionen(), lief)); } else { store_prepstmt.setNull(18, java.sql.Types.BIGINT); } final String s = load_rs.getString("Sigel"); // System.err.println("zustndige Bib: "+ s + // " ist "+help.getIdFromStringArray(help.getSigel(), s)); if (this.help.getIdFromStringArray(this.help.getSigel(), s) != 0) { store_prepstmt.setLong(19, this.help.getIdFromStringArray(this.help.getSigel(), s)); } else { store_prepstmt.setNull(19, java.sql.Types.BIGINT); } store_prepstmt.executeUpdate(); } } catch (final SQLException e) { e.printStackTrace(); // To change body of catch statement use File | // Settings | File Templates. } // insert into Interesse (besteller_bestellerId, interesse, journal_id) // values (?, ?, ?) // insert into Nutzung (journal_id, nutzungsjahr, rechnungsbetrag, // zeitraum, zugriffe) values (?, ?, ?, ?, ?) // insert into Rechnung (betrag, bezugsform, bezugsjahr, // exemplar_exemplarId, sigel_sigelId) values (?, ?, ?, ?, ?) }
From source file:org.apache.torque.util.BasePeerImpl.java
/** * Sets the prepared statement replacements into a query, possibly * modifying the type if required by DB Drivers. * * @param statement the statement to set the parameters in, not null. * @param replacements the replacements to set, not null. * @param offset the offset on the parameters, 0 for no offset. * * @return the parameters set.//from w w w . ja v a2 s . c o m * * @throws SQLException if setting the parameter fails. */ private List<Object> setPreparedStatementReplacements(PreparedStatement statement, List<Object> replacements, int offset) throws SQLException { List<Object> result = new ArrayList<Object>(replacements.size()); int i = 1 + offset; for (Object param : replacements) { if (param instanceof java.sql.Timestamp) { statement.setTimestamp(i, (java.sql.Timestamp) param); result.add(param); } else if (param instanceof java.sql.Date) { statement.setDate(i, (java.sql.Date) param); result.add(param); } else if (param instanceof java.util.Date) { java.sql.Timestamp sqlDate = new java.sql.Timestamp(((java.util.Date) param).getTime()); statement.setTimestamp(i, sqlDate); result.add(sqlDate); } else if (param instanceof NumberKey) { BigDecimal bigDecimal = ((NumberKey) param).getBigDecimal(); statement.setBigDecimal(i, bigDecimal); result.add(bigDecimal); } else if (param instanceof Integer) { statement.setInt(i, ((Integer) param).intValue()); result.add(param); } else if (param instanceof Long) { statement.setLong(i, ((Long) param).longValue()); result.add(param); } else if (param instanceof BigDecimal) { statement.setBigDecimal(i, (BigDecimal) param); result.add(param); } else if (param instanceof Boolean) { statement.setBoolean(i, ((Boolean) param).booleanValue()); result.add(param); } else { statement.setString(i, param.toString()); result.add(param.toString()); } ++i; } return result; }
From source file:org.dspace.storage.rdbms.DatabaseManager.java
private static void loadParameters(PreparedStatement statement, Collection<ColumnInfo> columns, TableRow row) throws SQLException { int count = 0; for (ColumnInfo info : columns) { count++;//from w w w .ja v a 2 s . com String column = info.getCanonicalizedName(); int jdbctype = info.getType(); if (row.isColumnNull(column)) { statement.setNull(count, jdbctype); } else { switch (jdbctype) { case Types.BIT: statement.setBoolean(count, row.getBooleanColumn(column)); break; case Types.INTEGER: if (isOracle) { statement.setLong(count, row.getLongColumn(column)); } else { statement.setInt(count, row.getIntColumn(column)); } break; case Types.NUMERIC: case Types.DECIMAL: statement.setLong(count, row.getLongColumn(column)); // FIXME should be BigDecimal if TableRow supported that break; case Types.BIGINT: statement.setLong(count, row.getLongColumn(column)); break; case Types.CLOB: if (isOracle) { // Support CLOBs in place of TEXT columns in Oracle statement.setString(count, row.getStringColumn(column)); } else { throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } break; case Types.VARCHAR: statement.setString(count, row.getStringColumn(column)); break; case Types.DATE: statement.setDate(count, new java.sql.Date(row.getDateColumn(column).getTime())); break; case Types.TIME: statement.setTime(count, new Time(row.getDateColumn(column).getTime())); break; case Types.TIMESTAMP: statement.setTimestamp(count, new Timestamp(row.getDateColumn(column).getTime())); break; default: throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } } } }
From source file:Logica.Usuario.java
/** * * @param d//from ww w. ja v a2 s .c o m * @return * @throws RemoteException * * Registra el descargo de un tem en la base de datos. */ @Override public boolean realizarDescargo(descargo d) throws RemoteException { EntityManagerFactory emf = Persistence.createEntityManagerFactory("Biot_ServerPU"); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; String statement = "INSERT INTO DESCARGO(FECHA, ID_usuario, AREA, CANTIDAD, CINTERNO) VALUES (?,?,?,?,?)"; boolean valido = false; try { con = Conexion.conexion.getConnection(); ps = con.prepareStatement(statement); ps.setDate(1, new Date(d.getFecha().getTimeInMillis())); ps.setString(2, d.getId()); ps.setString(3, d.getArea()); ps.setFloat(4, d.getCantidad()); ps.setString(5, d.getCinterno()); ps.executeUpdate(); this.updateCantidad(d.getCinterno(), d.getCantidad() * -1); valido = true; } catch (SQLException ex) { Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex); } finally { try { if (ps != null) { ps.close(); } if (rs != null) { rs.close(); } if (con != null) { con.close(); } } catch (SQLException ex) { System.out.println("Error cerrando conexion"); } } return valido; }
From source file:com.strider.datadefender.DatabaseAnonymizer.java
/** * Anonymizes a row of columns.// w w w.ja va 2 s.c om * * Sets query parameters on the passed updateStmt - this includes the key * values - and calls anonymization functions for the columns. * * @param updateStmt * @param tableColumns * @param keyNames * @param db * @param row * @param columnMetaData * @throws SQLException * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ private void anonymizeRow(final PreparedStatement updateStmt, final Collection<Column> tableColumns, final Collection<String> keyNames, final Connection db, final ResultSet row, final List<MatchMetaData> columnMetaData, final String vendor) throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, DatabaseAnonymizerException { int fieldIndex = 0; final Map<String, Integer> columnIndexes = new HashMap<>(tableColumns.size()); final Set<String> anonymized = new HashSet<>(tableColumns.size()); for (final Column column : tableColumns) { final String columnName = column.getName(); if (anonymized.contains(columnName)) { continue; } if (!columnIndexes.containsKey(columnName)) { final int columnIndex = ++fieldIndex; columnIndexes.put(columnName, columnIndex); } if (isExcludedColumn(row, column)) { final String columnValue = row.getString(columnName); updateStmt.setString(columnIndexes.get(columnName), columnValue); log.debug("Excluding column: " + columnName + " with value: " + columnValue); continue; } anonymized.add(columnName); final Object colValue = callAnonymizingFunctionFor(db, row, column, vendor); log.debug("colValue = " + colValue); log.debug("type= " + (colValue != null ? colValue.getClass() : "null")); if (colValue == null) { updateStmt.setNull(columnIndexes.get(columnName), Types.NULL); } else if (colValue.getClass() == java.sql.Date.class) { updateStmt.setDate(columnIndexes.get(columnName), CommonUtils.stringToDate(colValue.toString(), "dd-MM-yyyy")); } else if (colValue.getClass() == java.lang.Integer.class) { updateStmt.setInt(columnIndexes.get(columnName), (int) colValue); } else { updateStmt.setString(columnIndexes.get(columnName), getTruncatedColumnValue((String) colValue, columnIndexes.get(columnName), columnMetaData)); } } int whereIndex = fieldIndex; for (final String key : keyNames) { updateStmt.setString(++whereIndex, row.getString(key)); } updateStmt.addBatch(); }
From source file:org.dspace.storage.rdbms.MockDatabaseManager.java
@Mock private static void loadParameters(PreparedStatement statement, Collection<ColumnInfo> columns, TableRow row) throws SQLException { int count = 0; for (ColumnInfo info : columns) { count++;// w ww. j a v a 2 s . com String column = info.getName(); int jdbctype = info.getType(); if (row.isColumnNull(column)) { statement.setNull(count, jdbctype); } else { switch (jdbctype) { case Types.BIT: case Types.BOOLEAN: statement.setBoolean(count, row.getBooleanColumn(column)); break; case Types.INTEGER: if (isOracle) { statement.setLong(count, row.getLongColumn(column)); } else { statement.setInt(count, row.getIntColumn(column)); } break; case Types.NUMERIC: case Types.DECIMAL: statement.setLong(count, row.getLongColumn(column)); // FIXME should be BigDecimal if TableRow supported that break; case Types.BIGINT: statement.setLong(count, row.getLongColumn(column)); break; case Types.CLOB: if (isOracle) { // Support CLOBs in place of TEXT columns in Oracle statement.setString(count, row.getStringColumn(column)); } else { throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } break; case Types.VARCHAR: statement.setString(count, row.getStringColumn(column)); break; case Types.DATE: statement.setDate(count, new java.sql.Date(row.getDateColumn(column).getTime())); break; case Types.TIME: statement.setTime(count, new Time(row.getDateColumn(column).getTime())); break; case Types.TIMESTAMP: statement.setTimestamp(count, new Timestamp(row.getDateColumn(column).getTime())); break; default: throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype); } } } }
From source file:br.com.cobranca.util.Util.java
public static <T> int inserirRegistro(T obj, Connection con) throws Exception { int id = 0;//from ww w . ja va 2 s. co m String nomeTabela = obj.getClass().getSimpleName(); String strSql = "INSERT INTO " + nomeTabela.toUpperCase() + " ("; boolean usarVirgula = false; for (Field field : obj.getClass().getDeclaredFields()) { field.setAccessible(true); if (usarVirgula) { strSql = strSql + ", "; } strSql = strSql + field.getName(); if (!usarVirgula) { usarVirgula = true; } } strSql = strSql + ") VALUES ("; usarVirgula = false; for (Field field : obj.getClass().getDeclaredFields()) { field.setAccessible(true); if (usarVirgula) { strSql = strSql + ", "; } strSql = strSql + "?"; if (!usarVirgula) { usarVirgula = true; } } strSql = strSql + ")"; PreparedStatement ps = con.prepareStatement(strSql, Statement.RETURN_GENERATED_KEYS); try { int i = 1; for (Field field : obj.getClass().getDeclaredFields()) { String tipoColuna = field.getType().getSimpleName(); if (tipoColuna.toUpperCase().contains("INT")) { tipoColuna = "Int"; } else { tipoColuna = StringPrimeiraLetraMaiuscula(tipoColuna); } // obj . get + nome do campo Method met = obj.getClass().getMethod("get" + StringPrimeiraLetraMaiuscula(field.getName())); if (tipoColuna.equals("Int")) { Integer valor = (Integer) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setInt(i, valor); } } else if (tipoColuna.equals("String")) { String valor = (String) met.invoke(obj); ps.setString(i, valor); } else if (tipoColuna.equals("Double")) { Double valor = (Double) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setDouble(i, valor); } } else if (tipoColuna.equals("Float")) { Float valor = (Float) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setFloat(i, valor); } } else if (tipoColuna.equals("Long")) { Long valor = (Long) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setLong(i, valor); } } else if (tipoColuna.equals("Boolean")) { Boolean valor = (Boolean) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setBoolean(i, valor); } } else if (tipoColuna.equals("Date")) { Date valor = (Date) met.invoke(obj); if (valor == null) { ps.setString(i, null); } else { ps.setDate(i, new java.sql.Date(valor.getTime())); } } else { return 0; } i++; } int qtdLinhasAfetadas = ps.executeUpdate(); if (qtdLinhasAfetadas > 0) { try (ResultSet rs = ps.getGeneratedKeys()) { if (rs.next()) { id = rs.getInt(1); } } } } catch (Exception ex) { throw new Exception(ex.getMessage()); } finally { ps.close(); } return id; }