List of usage examples for java.sql Statement addBatch
void addBatch(String sql) throws SQLException;
Statement
object. From source file:thesis.GetData.java
public void get_data_from_web() { Connection conn = getConnectiontoDB(); String limit = "limit"; if (jCheckBox3.isSelected()) { System.out.println("limit fetch selected!"); limit = limit + " " + jTextField2.getText(); System.out.println("limit fetch " + limit); } else//from ww w. j a v a2 s .c o m limit = ""; try { Statement stmt = conn.createStatement(); if (jCheckBox1.isSelected()) { String a = "TRUNCATE TABLE olx;"; String b = "TRUNCATE TABLE lazada"; String c = "TRUNCATE TABLE ebay"; String d = "TRUNCATE TABLE ads"; String e = "TRUNCATE TABLE ontology_system_final_table"; stmt.addBatch(a); stmt.addBatch(b); stmt.addBatch(c); stmt.addBatch(d); stmt.addBatch(e); } String f = "LOAD DATA LOCAL INFILE 'C:/Users/test/Documents/final ad crawler csv/ebay crawl.csv' INTO TABLE ebay FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES;\n"; String g = "LOAD DATA LOCAL INFILE 'C:/Users/test/Documents/final ad crawler csv/olx crawl.csv' INTO TABLE olx FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES;# 581 rows affected.\n"; String h = "LOAD DATA LOCAL INFILE 'C:/Users/test/Documents/final ad crawler csv/lazada crawl.csv' INTO TABLE lazada FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n' IGNORE 1 LINES;# 32 rows affected.\n"; String i = "INSERT INTO ads (ad_name, site, price, location, posted_by, description, image, link)\n" + "(SELECT link, g, h, cdf, i, asd, image, e FROM ebay " + limit + ")\n" + "union\n" + "(SELECT g, ad_name, h, dsf, cdf, zxcz, i, link FROM olx " + limit + ")\n" + "union\n" + "(SELECT g, ad_name, cxzc, cdf, zxcz, dsf, h, link FROM lazada " + limit + " )"; stmt.addBatch(f); stmt.addBatch(g); stmt.addBatch(h); stmt.addBatch(i); stmt.executeBatch(); } catch (SQLException sQLException) { System.err.println("sQLException = " + sQLException); } }
From source file:com.raulexposito.alarife.sqlexecutor.SQLExecutor.java
/** * Updates the database from one version to other by using the scripts * @param databaseType database type/*from www . j a va 2 s . com*/ * @param st sql statement to launch the creates and updates * @param nextVersion version of the scripts to be launched to upgrade to the next version * @throws com.raulexposito.alarife.exception.DatabaseException if something goes wrong */ private void updateToVersion(final DatabaseType databaseType, final ApplicationMode applicationMode, final Statement st, final Version nextVersion) throws DatabaseException { log.info("migrating to '" + nextVersion + "' version"); final long startTime = System.currentTimeMillis(); final ScriptsDirectoryUtil scriptsDirectoryUtil = new ScriptsDirectoryUtil(); try { st.executeUpdate(dcfspr.getChangeDatabase(databaseType)); log.debug("changed to schema '" + dcfspr.getInstance() + "'"); // read the content of the file with the SQL commands to update tables final InputStream upgradeTables = scriptsDirectoryUtil.getUpgradeTablesScript(databaseType, applicationMode, nextVersion); log.info("reading the content of the upgrade tables script"); final List<String> upgradeTablesCommands = getSQLCommandsFromScriptFile(upgradeTables); for (String command : upgradeTablesCommands) { st.addBatch(command); } // read the content of the file with the SQL commands to insert data final InputStream insertData = scriptsDirectoryUtil.getInsertDataScript(databaseType, applicationMode, nextVersion); log.info("reading the content of the insert data script"); final List<String> insertDataCommands = getSQLCommandsFromScriptFile(insertData); for (String command : insertDataCommands) { st.addBatch(command); } // execution of the different commands st.executeBatch(); log.info("scripts succesfully executed [" + (System.currentTimeMillis() - startTime) + " ms]"); } catch (Exception e) { log.error(CANNOT_UPGRADE_TO_VERSION + "'" + nextVersion + "': " + e); throw new DatabaseException(CANNOT_UPGRADE_TO_VERSION + "'" + nextVersion + "'", e); } }
From source file:com.intellectualcrafters.plot.database.SQLManager.java
/** * Create tables//from ww w . java2 s. c o m * * @throws SQLException */ @Override public void createTables(final String database, final boolean add_constraint) throws SQLException { final boolean mysql = database.equals("mysql"); final Statement stmt = connection.createStatement(); if (mysql) { stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot` (" + "`id` INT(11) NOT NULL AUTO_INCREMENT," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP," + "PRIMARY KEY (`id`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=0"); stmt.addBatch( "CREATE TABLE IF NOT EXISTS `" + prefix + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); stmt.addBatch( "CREATE TABLE IF NOT EXISTS `" + prefix + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_comments` (" + "`plot_plot_id` INT(11) NOT NULL," + "`comment` VARCHAR(40) NOT NULL," + "`tier` INT(11) NOT NULL," + "`sender` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); stmt.addBatch( "CREATE TABLE IF NOT EXISTS `" + prefix + "plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," + " `flags` VARCHAR(512) DEFAULT NULL," + " `merged` INT(11) DEFAULT NULL," + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)," + " UNIQUE KEY `unique_alias` (`alias`)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_ratings` ( `plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8"); if (add_constraint) { stmt.addBatch("ALTER TABLE `" + prefix + "plot_settings` ADD CONSTRAINT `" + prefix + "plot_settings_ibfk_1` FOREIGN KEY (`plot_plot_id`) REFERENCES `" + prefix + "plot` (`id`) ON DELETE CASCADE"); } } else { stmt.addBatch( "CREATE TABLE IF NOT EXISTS `" + prefix + "plot` (" + "`id` INTEGER PRIMARY KEY AUTOINCREMENT," + "`plot_id_x` INT(11) NOT NULL," + "`plot_id_z` INT(11) NOT NULL," + "`owner` VARCHAR(45) NOT NULL," + "`world` VARCHAR(45) NOT NULL," + "`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP)"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_denied` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_helpers` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_trusted` (" + "`plot_plot_id` INT(11) NOT NULL," + "`user_uuid` VARCHAR(40) NOT NULL" + ")"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_comments` (" + "`plot_plot_id` INT(11) NOT NULL," + "`comment` VARCHAR(40) NOT NULL," + "`tier` INT(11) NOT NULL," + "`sender` VARCHAR(40) NOT NULL" + ")"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_settings` (" + " `plot_plot_id` INT(11) NOT NULL," + " `biome` VARCHAR(45) DEFAULT 'FOREST'," + " `rain` INT(1) DEFAULT 0," + " `custom_time` TINYINT(1) DEFAULT '0'," + " `time` INT(11) DEFAULT '8000'," + " `deny_entry` TINYINT(1) DEFAULT '0'," + " `alias` VARCHAR(50) DEFAULT NULL," + " `flags` VARCHAR(512) DEFAULT NULL," + " `merged` INT(11) DEFAULT NULL," + " `position` VARCHAR(50) NOT NULL DEFAULT 'DEFAULT'," + " PRIMARY KEY (`plot_plot_id`)" + ")"); stmt.addBatch("CREATE TABLE IF NOT EXISTS `" + prefix + "plot_ratings` (`plot_plot_id` INT(11) NOT NULL, `rating` INT(2) NOT NULL, `player` VARCHAR(40) NOT NULL, PRIMARY KEY(`plot_plot_id`))"); } stmt.executeBatch(); stmt.clearBatch(); stmt.close(); }
From source file:com.mpdeimos.ct_tests.processors.CloneTrackingLoop.java
private void addSuspection(KeyValueGateway keyValueGateway, String cid, String message, Statement stmt, KeyValueStoreBase kv) throws SQLException { Object[] args = null;// w w w .j a va2 s . c om EStringStoredValue key = EStringStoredValue.BUGSUSPECTION; EStringStoredValue key_rev = EStringStoredValue.BUGSUSPECTION_REV; if (key.get(kv, args) != null) { int i = 1; args = new Object[i]; key = EStringStoredValue.BUGSUSPECTION_N; key_rev = EStringStoredValue.BUGSUSPECTION_N_REV; do { args[0] = i++; } while (key.get(kv, args) != null); } key.set(kv, message, args); if (cid != null) key_rev.set(kv, cid, args); if (!disablePersist) stmt.addBatch(keyValueGateway.createInsertValueSql(kv.getId(), key.getKey(args), message)); }
From source file:org.apache.tajo.catalog.store.DBStore.java
@Override public final void addTable(final TableDesc table) throws IOException { Statement stmt = null; ResultSet res;/*w w w. ja va 2s .c o m*/ String sql = "INSERT INTO " + TB_TABLES + " (" + C_TABLE_ID + ", path, store_type) " + "VALUES('" + table.getId() + "', " + "'" + table.getPath() + "', " + "'" + table.getMeta().getStoreType() + "'" + ")"; wlock.lock(); try { stmt = conn.createStatement(); if (LOG.isDebugEnabled()) { LOG.debug(sql); } stmt.addBatch(sql); stmt.executeBatch(); stmt = conn.createStatement(); sql = "SELECT TID from " + TB_TABLES + " WHERE " + C_TABLE_ID + " = '" + table.getId() + "'"; if (LOG.isDebugEnabled()) { LOG.debug(sql); } res = stmt.executeQuery(sql); if (!res.next()) { throw new IOException("ERROR: there is no tid matched to " + table.getId()); } int tid = res.getInt("TID"); String colSql; int columnId = 0; for (Column col : table.getMeta().getSchema().getColumns()) { colSql = columnToSQL(tid, table, columnId, col); if (LOG.isDebugEnabled()) { LOG.debug(colSql); } stmt.addBatch(colSql); columnId++; } Iterator<Entry<String, String>> it = table.getMeta().getOptions(); String optSql; while (it.hasNext()) { optSql = keyvalToSQL(table, it.next()); if (LOG.isDebugEnabled()) { LOG.debug(optSql); } stmt.addBatch(optSql); } stmt.executeBatch(); if (table.getMeta().getStat() != null) { sql = "INSERT INTO " + TB_STATISTICS + " (" + C_TABLE_ID + ", num_rows, num_bytes) " + "VALUES ('" + table.getId() + "', " + table.getMeta().getStat().getNumRows() + "," + table.getMeta().getStat().getNumBytes() + ")"; if (LOG.isDebugEnabled()) { LOG.debug(sql); } stmt.addBatch(sql); stmt.executeBatch(); } } catch (SQLException se) { throw new IOException(se.getMessage(), se); } finally { wlock.unlock(); try { stmt.close(); } catch (SQLException e) { } } }
From source file:org.alinous.plugin.derby.DerbyDataSource.java
private void executeAddBatch(Connection con, String sql) throws SQLException { Statement batchStmt = this.batchedStatementMap.get(con); if (batchStmt == null) { batchStmt = con.createStatement(); this.batchedStatementMap.put(con, batchStmt); }// w ww. j a va2s . com batchStmt.addBatch(sql); }
From source file:net.ymate.platform.persistence.jdbc.base.impl.BatchUpdateOperator.java
protected int __doExecute() throws Exception { Statement _statement = null; AccessorEventContext _context = null; try {/* w w w. ja v a2 s . c o m*/ IAccessor _accessor = new BaseAccessor(this.getAccessorConfig()); if (StringUtils.isNotBlank(this.getSQL())) { _statement = _accessor.getPreparedStatement(this.getConnectionHolder().getConnection(), this.getSQL()); // for (SQLBatchParameter _batchParam : this.__batchParameters) { for (int i = 0; i < _batchParam.getParameters().size(); i++) { SQLParameter _param = _batchParam.getParameters().get(i); if (_param.getValue() == null) { ((PreparedStatement) _statement).setNull(i + 1, 0); } else { ((PreparedStatement) _statement).setObject(i + 1, _param.getValue()); } } ((PreparedStatement) _statement).addBatch(); } } else { _statement = _accessor.getStatement(this.getConnectionHolder().getConnection()); } // for (String _batchSQL : this.__batchSQL) { _statement.addBatch(_batchSQL); } // if (this.getAccessorConfig() != null) { this.getAccessorConfig().beforeStatementExecution( _context = new AccessorEventContext(_statement, JDBC.DB_OPERATION_TYPE.BATCH_UPDATE)); } effectCounts = _statement.executeBatch(); // ?? int _count = 0; for (int _c : effectCounts) { _count += _c; } return _count; } finally { if (this.getAccessorConfig() != null && _context != null) { this.getAccessorConfig().afterStatementExecution(_context); } if (_statement != null) { _statement.clearBatch(); _statement.close(); } } }
From source file:com.flexive.core.storage.genericSQL.GenericTreeStorageSpreaded.java
/** * {@inheritDoc}//w w w .j a v a2 s .co m */ @Override public long copy(Connection con, SequencerEngine seq, FxTreeMode mode, long srcNodeId, long dstParentNodeId, int dstPosition, boolean deepReferenceCopy, String copyOfPrefix) throws FxApplicationException { // Check both nodes (this throws a FxNotFoundException if they do not exist) final FxTreeNodeInfo sourceNode = getTreeNodeInfo(con, mode, srcNodeId); getTreeNodeInfo(con, mode, dstParentNodeId); // Make space for the new nodes BigInteger spacing = makeSpace(con, seq, mode, dstParentNodeId, dstPosition, sourceNode.getTotalChildCount() + 1); // Reload the node to obtain the new boundary and spacing informations final FxTreeNodeInfoSpreaded destinationNode = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, dstParentNodeId); acquireLocksForUpdate(con, mode, Arrays.asList(srcNodeId, sourceNode.getParentId(), dstParentNodeId)); // Copy the data BigInteger boundaries[] = getBoundaries(con, destinationNode, dstPosition); int depthDelta = (destinationNode.getDepth() + 1) - sourceNode.getDepth(); long firstCreatedNodeId = reorganizeSpace(con, seq, mode, mode, sourceNode.getId(), true, spacing, boundaries[0], null, -1, null, null, depthDelta, dstParentNodeId, true, false, true); Statement stmt = null; PreparedStatement ps = null; try { // Update the childcount of the new parents stmt = con.createStatement(); stmt.addBatch("UPDATE " + getTable(mode) + " SET CHILDCOUNT=CHILDCOUNT+1 WHERE ID=" + dstParentNodeId); stmt.executeBatch(); if (deepReferenceCopy) { FxTreeNodeInfoSpreaded nodeInfo = (FxTreeNodeInfoSpreaded) getTreeNodeInfo(con, mode, firstCreatedNodeId); ps = con.prepareStatement("SELECT ID,REF FROM " + getTable(mode) + " WHERE LFT>=? AND RGT<=?"); setNodeBounds(ps, 1, nodeInfo.getLeft()); setNodeBounds(ps, 2, nodeInfo.getRight()); ResultSet rs = ps.executeQuery(); final ContentEngine ce = EJBLookup.getContentEngine(); while (rs != null && rs.next()) { FxPK pkRef = new FxPK(rs.getLong(2)); long nodeId = rs.getLong(1); FxPK pkNew = ce.save(ce.load(pkRef).copyAsNewInstance()); updateReference(con, mode, nodeId, pkNew.getId()); } } } catch (SQLException exc) { throw new FxTreeException( "MoveNode: Failed to update the parent of node#" + srcNodeId + ": " + exc.getMessage()); } finally { Database.closeObjects(GenericTreeStorageSpreaded.class, stmt, ps); } return firstCreatedNodeId; }
From source file:com.intellectualcrafters.plot.database.SQLManager.java
/** * @return/*from ww w. ja va2 s . com*/ */ @Override public LinkedHashMap<String, HashMap<PlotId, Plot>> getPlots() { final LinkedHashMap<String, HashMap<PlotId, Plot>> newplots = new LinkedHashMap<String, HashMap<PlotId, Plot>>(); try { final DatabaseMetaData data = connection.getMetaData(); ResultSet rs = data.getColumns(null, null, prefix + "plot", "plot_id"); final boolean execute = rs.next(); if (execute) { final Statement statement = connection.createStatement(); statement.addBatch("ALTER IGNORE TABLE `" + prefix + "plot` ADD `plot_id_x` int(11) DEFAULT 0"); statement.addBatch("ALTER IGNORE TABLE `" + prefix + "plot` ADD `plot_id_z` int(11) DEFAULT 0"); statement.addBatch("UPDATE `" + prefix + "plot` SET\n" + " `plot_id_x` = IF(" + " LOCATE(';', `plot_id`) > 0," + " SUBSTRING(`plot_id`, 1, LOCATE(';', `plot_id`) - 1)," + " `plot_id`" + " )," + " `plot_id_z` = IF(" + " LOCATE(';', `plot_id`) > 0," + " SUBSTRING(`plot_id`, LOCATE(';', `plot_id`) + 1)," + " NULL" + " )"); statement.addBatch("ALTER TABLE `" + prefix + "plot` DROP `plot_id`"); statement.addBatch( "ALTER IGNORE TABLE `" + prefix + "plot_settings` ADD `flags` VARCHAR(512) DEFAULT NULL"); statement.executeBatch(); statement.close(); } rs = data.getColumns(null, null, prefix + "plot_settings", "merged"); if (!rs.next()) { final Statement statement = connection.createStatement(); statement.addBatch("ALTER TABLE `" + prefix + "plot_settings` ADD `merged` int(11) DEFAULT NULL"); statement.executeBatch(); statement.close(); } } catch (final Exception e) { e.printStackTrace(); } final HashMap<Integer, Plot> plots = new HashMap<Integer, Plot>(); Statement stmt = null; try { Set<String> worlds = new HashSet<String>(); if (PlotMain.config.contains("worlds")) { worlds = PlotMain.config.getConfigurationSection("worlds").getKeys(false); } final HashMap<String, UUID> uuids = new HashMap<String, UUID>(); final HashMap<String, Integer> noExist = new HashMap<String, Integer>(); /* * Getting plots */ stmt = connection.createStatement(); ResultSet r = stmt.executeQuery( "SELECT `id`, `plot_id_x`, `plot_id_z`, `owner`, `world` FROM `" + prefix + "plot`"); PlotId plot_id; int id; Plot p; String o; UUID user; while (r.next()) { plot_id = new PlotId(r.getInt("plot_id_x"), r.getInt("plot_id_z")); id = r.getInt("id"); final String worldname = r.getString("world"); if (!worlds.contains(worldname)) { if (noExist.containsKey(worldname)) { noExist.put(worldname, noExist.get(worldname) + 1); } else { noExist.put(worldname, 1); } } o = r.getString("owner"); user = uuids.get(o); if (user == null) { user = UUID.fromString(o); uuids.put(o, user); } p = new Plot(plot_id, user, Biome.FOREST, new ArrayList<UUID>(), new ArrayList<UUID>(), new ArrayList<UUID>(), "", PlotHomePosition.DEFAULT, null, worldname, new boolean[] { false, false, false, false }); plots.put(id, p); } // stmt.close(); /* * Getting helpers */ // stmt = connection.createStatement(); r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + prefix + "plot_helpers`"); while (r.next()) { id = r.getInt("plot_plot_id"); o = r.getString("user_uuid"); user = uuids.get(o); if (user == null) { user = UUID.fromString(o); uuids.put(o, user); } final Plot plot = plots.get(id); if (plot != null) { plot.addHelper(user); } else { PlotMain.sendConsoleSenderMessage("&cPLOT " + id + " in plot_helpers does not exist. Please create the plot or remove this entry."); } } // stmt.close(); /* * Getting trusted */ // stmt = connection.createStatement(); r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + prefix + "plot_trusted`"); while (r.next()) { id = r.getInt("plot_plot_id"); o = r.getString("user_uuid"); user = uuids.get(o); if (user == null) { user = UUID.fromString(o); uuids.put(o, user); } final Plot plot = plots.get(id); if (plot != null) { plot.addTrusted(user); } else { PlotMain.sendConsoleSenderMessage("&cPLOT " + id + " in plot_trusted does not exist. Please create the plot or remove this entry."); } } // stmt.close(); /* * Getting denied */ // stmt = connection.createStatement(); r = stmt.executeQuery("SELECT `user_uuid`, `plot_plot_id` FROM `" + prefix + "plot_denied`"); while (r.next()) { id = r.getInt("plot_plot_id"); o = r.getString("user_uuid"); user = uuids.get(o); if (user == null) { user = UUID.fromString(o); uuids.put(o, user); } final Plot plot = plots.get(id); if (plot != null) { plot.addDenied(user); } else { PlotMain.sendConsoleSenderMessage("&cPLOT " + id + " in plot_denied does not exist. Please create the plot or remove this entry."); } } // stmt.close(); // stmt = connection.createStatement(); r = stmt.executeQuery("SELECT * FROM `" + prefix + "plot_settings`"); while (r.next()) { id = r.getInt("plot_plot_id"); final Plot plot = plots.get(id); if (plot != null) { final String b = r.getString("biome"); Biome biome = null; if (b != null) { for (final Biome mybiome : Biome.values()) { if (mybiome.toString().equalsIgnoreCase(b)) { biome = mybiome; break; } } } final String alias = r.getString("alias"); if (alias != null) { plot.settings.setAlias(alias); } final String pos = r.getString("position"); if (pos != null) { for (final PlotHomePosition plotHomePosition : PlotHomePosition.values()) { if (plotHomePosition.isMatching(pos)) { if (plotHomePosition != PlotHomePosition.DEFAULT) { plot.settings.setPosition(plotHomePosition); } break; } } } final Integer m = r.getInt("merged"); if (m != null) { final boolean[] merged = new boolean[4]; for (int i = 0; i < 4; i++) { merged[3 - i] = ((m) & (1 << i)) != 0; } plot.settings.setMerged(merged); } else { plot.settings.setMerged(new boolean[] { false, false, false, false }); } String[] flags_string; final String myflags = r.getString("flags"); if (myflags == null) { flags_string = new String[] {}; } else { flags_string = myflags.split(","); } final ArrayList<Flag> flags = new ArrayList<Flag>(); boolean exception = false; for (final String element : flags_string) { if (element.contains(":")) { final String[] split = element.split(":"); try { flags.add(new Flag(FlagManager.getFlag(split[0], true), split[1].replaceAll("\u00AF", ":").replaceAll("", ","))); } catch (final Exception e) { exception = true; } } else { flags.add(new Flag(FlagManager.getFlag(element, true), "")); } } if (exception) { PlotMain.sendConsoleSenderMessage( "&cPlot " + id + " had an invalid flag. A fix has been attempted."); setFlags(id, flags.toArray(new Flag[0])); } plot.settings.setFlags(flags.toArray(new Flag[0])); } else { PlotMain.sendConsoleSenderMessage("&cPLOT " + id + " in plot_settings does not exist. Please create the plot or remove this entry."); } } stmt.close(); for (final Plot plot : plots.values()) { final String world = plot.world; if (!newplots.containsKey(world)) { newplots.put(world, new HashMap<PlotId, Plot>()); } newplots.get(world).put(plot.id, plot); } boolean invalidPlot = false; for (final String worldname : noExist.keySet()) { invalidPlot = true; PlotMain.sendConsoleSenderMessage("&c[WARNING] Found " + noExist.get(worldname) + " plots in DB for non existant world; '" + worldname + "'."); } if (invalidPlot) { PlotMain.sendConsoleSenderMessage( "&c[WARNING] - Please create the world/s or remove the plots using the purge command"); } } catch (final SQLException e) { Logger.add(LogLevel.WARNING, "Failed to load plots."); e.printStackTrace(); } return newplots; }
From source file:jmdbtools.JMdbTools.java
private int[] insertData(Table dataTable, DbTable dbTable, Connection conn) { Statement stmt = null; int[] execStatus = new int[0]; try {//from w w w .ja v a 2 s . c o m stmt = conn.createStatement(); log("Creating Insert Statements:" + dbTable.getName(), "info"); for (Row row : dataTable) { InsertQuery insertQuery = new InsertQuery(dbTable); for (Map.Entry<String, Object> col : row.entrySet()) { //We had to add crap to the column name, so have to muck about to get match DbColumn column = dbTable.findColumn(fixColumnName(col.getKey())); if (col.getValue() != null) { if (column.getTypeNameSQL().equalsIgnoreCase("DATE") || column.getTypeNameSQL().equalsIgnoreCase("DATETIME")) { java.sql.Timestamp sqlDate = new java.sql.Timestamp(((Date) col.getValue()).getTime()); //log(sqlDate.toString(), "debug"); insertQuery.addColumn(column, sqlDate); } else { insertQuery.addColumn(column, col.getValue()); } } } stmt.addBatch(insertQuery.validate().toString()); } log("Executing Insert", "info"); execStatus = stmt.executeBatch(); } catch (SQLException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } return execStatus; }