@Override public void addEntry(final Entry entry) throws IOException { final String table_name = this.sql_table_name; final List<String> keys = Collections.newList(); final String stm = "INSERT INTO " + table_name + " " + this.paramString(entry, keys, "(", ")"); final MySQLConnection connection = this.db.obtainConnection(); connection.checkIsOpen(); try { final Connection mysql_connection = connection.getConnection(); final PreparedStatement statement = mysql_connection.prepareStatement(stm); for (int i = 0; i < keys.size(); i++) { final String key = keys.getElementAt(i); final String value = entry.getValue(key); statement.setString(i + 1, value); } statement.execute(); } catch (final SQLException e) { e.printStackTrace(); throw new IOException(e); } finally { this.db.releaseConnection(connection); } }
@Override public void replaceEntries(final List<Entry> batch) throws IOException { if (batch.size() == 0) { return; } final Entry entry0 = batch.getElementAt(0); final String table_name = this.sql_table_name; final List<String> keys = Collections.newList(); final String stm = "REPLACE " + table_name + " " + this.paramString(entry0, keys, "(", ")"); final MySQLConnection connection = this.db.obtainConnection(); connection.checkIsOpen(); try { final Connection mysql_connection = connection.getConnection(); final PreparedStatement statement = mysql_connection.prepareStatement(stm); for (int b = 0; b < batch.size(); b++) { final Entry entry = batch.getElementAt(b); for (int i = 0; i < keys.size(); i++) { final String key = keys.getElementAt(i); final String value = entry.getValue(key); statement.setString(i + 1, value); } statement.addBatch(); } statement.executeBatch(); } catch (final SQLException e) { e.printStackTrace(); throw new IOException(e); } finally { this.db.releaseConnection(connection); } }
private String paramString( final Entry entry, final List<String> keys, final String bracketLeft, final String bracketRight) throws IOException { final MySQLTableSchema schema = this.getSchema(); final Collection<String> colums = schema.getColumns(); for (int i = 0; i < colums.size(); i++) { final String key = colums.getElementAt(i); final String value = entry.getValue(key); if (value != null) { keys.add(key); } } final String schemaString = JUtils.wrapSequence(keys, keys.size(), bracketLeft, bracketRight); return schemaString + " VALUES " + JUtils.wrapSequence((i) -> "?", keys.size(), "(", ")"); }