List of usage examples for java.sql SQLException printStackTrace
public void printStackTrace()
From source file:com.cloud.utils.db.TransactionLegacy.java
/** * Receives a list of {@link PreparedStatement} and quietly closes all of them, which * triggers also closing their dependent objects, like a {@link ResultSet} * * @param pstmt2Close//ww w.j a va 2 s . c om */ public static void closePstmts(List<PreparedStatement> pstmt2Close) { for (PreparedStatement pstmt : pstmt2Close) { try { if (pstmt != null && !pstmt.isClosed()) { pstmt.close(); } } catch (SQLException e) { // It's not possible to recover from this and we need to continue closing e.printStackTrace(); } } }
From source file:com.drevelopment.couponcodes.bukkit.coupon.BukkitCouponHandler.java
@Override public void updateCoupon(Coupon coupon) { try {/*from w ww.ja v a2 s . co m*/ databaseHandler.query("UPDATE couponcodes SET usetimes='" + coupon.getUseTimes() + "' WHERE name='" + coupon.getName() + "'"); databaseHandler.query("UPDATE couponcodes SET usedplayers='" + playerHashToString(coupon.getUsedPlayers()) + "' WHERE name='" + coupon.getName() + "'"); databaseHandler.query("UPDATE couponcodes SET timeuse='" + coupon.getTime() + "' WHERE name='" + coupon.getName() + "'"); if (coupon instanceof ItemCoupon) databaseHandler .query("UPDATE couponcodes SET ids='" + itemHashToString(((ItemCoupon) coupon).getIDs()) + "' WHERE name='" + coupon.getName() + "'"); else if (coupon instanceof EconomyCoupon) databaseHandler.query("UPDATE couponcodes SET money='" + ((EconomyCoupon) coupon).getMoney() + "' WHERE name='" + coupon.getName() + "'"); else if (coupon instanceof RankCoupon) databaseHandler.query("UPDATE couponcodes SET groupname='" + ((RankCoupon) coupon).getGroup() + "' WHERE name='" + coupon.getName() + "'"); else if (coupon instanceof XpCoupon) databaseHandler.query("UPDATE couponcodes SET xp='" + ((XpCoupon) coupon).getXp() + "' WHERE name='" + coupon.getName() + "'"); else if (coupon instanceof CommandCoupon) databaseHandler.query("UPDATE couponcodes SET command='" + ((CommandCoupon) coupon).getCmd() + "' WHERE name='" + coupon.getName() + "'"); } catch (SQLException e) { e.printStackTrace(); } }
From source file:com.drevelopment.couponcodes.bukkit.coupon.BukkitCouponHandler.java
@Override public Coupon getCoupon(String coupon) { if (!couponExists(coupon)) return null; try {/*from w w w .j a v a 2 s . c o m*/ ResultSet rs = databaseHandler.query("SELECT * FROM couponcodes WHERE name='" + coupon + "'"); if (databaseHandler.getDatabaseOptions() instanceof MySQLOptions) rs.first(); int usetimes = rs.getInt("usetimes"); int time = rs.getInt("timeuse"); HashMap<String, Boolean> usedplayers = playerStringToHash(rs.getString("usedplayers")); if (rs.getString("ctype").equalsIgnoreCase("Item")) return createNewItemCoupon(coupon, usetimes, time, itemStringToHash(rs.getString("ids"), null), usedplayers); else if (rs.getString("ctype").equalsIgnoreCase("Economy")) return createNewEconomyCoupon(coupon, usetimes, time, usedplayers, rs.getInt("money")); else if (rs.getString("ctype").equalsIgnoreCase("Rank")) return createNewRankCoupon(coupon, rs.getString("groupname"), usetimes, time, usedplayers); else if (rs.getString("ctype").equalsIgnoreCase("Xp")) return createNewXpCoupon(coupon, rs.getInt("xp"), usetimes, time, usedplayers); else if (rs.getString("ctype").equalsIgnoreCase("Command")) return createNewCommandCoupon(coupon, rs.getString("command"), usetimes, time, usedplayers); else return null; } catch (SQLException e) { e.printStackTrace(); return null; } }
From source file:com.abixen.platform.service.businessintelligence.multivisualization.service.impl.AbstractDatabaseService.java
private List<Map<String, DataValueWeb>> getData(Connection connection, DatabaseDataSource databaseDataSource, Set<String> chartColumnsSet, ChartConfigurationForm chartConfigurationForm) { ResultSet rs;/*w ww .j a v a 2 s .c o m*/ List<Map<String, DataValueWeb>> data = new ArrayList<>(); try { Statement statement = connection.createStatement(); ResultSetMetaData resultSetMetaData = getDatabaseMetaData(connection, databaseDataSource.getTable()); if (chartConfigurationForm != null) { rs = statement.executeQuery(buildQueryForChartData(databaseDataSource, chartColumnsSet, resultSetMetaData, chartConfigurationForm)); } else { rs = statement.executeQuery( buildQueryForDataSourceData(databaseDataSource, chartColumnsSet, resultSetMetaData) .toString()); } while (rs.next()) { final ResultSet row = rs; Map<String, DataValueWeb> rowMap = new HashMap<>(); chartColumnsSet.forEach(chartColumnsSetElement -> { rowMap.put(chartColumnsSetElement, getDataFromColumn(row, chartColumnsSetElement)); }); data.add(rowMap); } } catch (SQLException e) { e.printStackTrace(); throw new DataParsingException("Error when parsing data from db. " + e.getMessage()); } return data; }
From source file:com.drevelopment.couponcodes.bukkit.BukkitPlugin.java
@Override public void onEnable() { logger = this.getLogger(); CouponCodes.setEventHandler(new SimpleEventHandler()); CouponCodes.setModTransformer(new BukkitServerModTransformer(this)); CouponCodes.setConfigHandler(new BukkitConfigHandler(this)); CouponCodes.setCommandHandler(new SimpleCommandHandler()); //SQL/* www . j a va 2 s . co m*/ if (((BukkitConfigHandler) CouponCodes.getConfigHandler()).getSQLValue().equalsIgnoreCase("MYSQL")) { CouponCodes.setDatabaseHandler(new SQLDatabaseHandler(this, new MySQLOptions(((BukkitConfigHandler) CouponCodes.getConfigHandler()).getHostname(), ((BukkitConfigHandler) CouponCodes.getConfigHandler()).getPort(), ((BukkitConfigHandler) CouponCodes.getConfigHandler()).getDatabase(), ((BukkitConfigHandler) CouponCodes.getConfigHandler()).getUsername(), ((BukkitConfigHandler) CouponCodes.getConfigHandler()).getPassword()))); } else if (((BukkitConfigHandler) CouponCodes.getConfigHandler()).getSQLValue() .equalsIgnoreCase("SQLite")) { CouponCodes.setDatabaseHandler( new SQLDatabaseHandler(this, new SQLiteOptions(new File(getDataFolder() + "/coupon_data.db")))); } else if (!((BukkitConfigHandler) CouponCodes.getConfigHandler()).getSQLValue().equalsIgnoreCase("MYSQL") && !((BukkitConfigHandler) CouponCodes.getConfigHandler()).getSQLValue() .equalsIgnoreCase("SQLite")) { logger.severe(LocaleHandler.getString("Console.SQL.UnknownValue", ((BukkitConfigHandler) CouponCodes.getConfigHandler()).getSQLValue())); logger.severe(LocaleHandler.getString("Console.SQL.SetupFailed")); Bukkit.getPluginManager().disablePlugin(this); return; } try { ((SQLDatabaseHandler) CouponCodes.getDatabaseHandler()).open(); ((SQLDatabaseHandler) CouponCodes.getDatabaseHandler()).createTable( "CREATE TABLE IF NOT EXISTS couponcodes (name VARCHAR(24), ctype VARCHAR(10), usetimes INT(10), usedplayers TEXT(1024), ids VARCHAR(255), money INT(10), groupname VARCHAR(20), timeuse INT(100), xp INT(10), command VARCHAR(255))"); CouponCodes.setCouponHandler( new BukkitCouponHandler(this, ((SQLDatabaseHandler) CouponCodes.getDatabaseHandler()))); } catch (SQLException e) { e.printStackTrace(); logger.severe(LocaleHandler.getString("Console.SQL.SetupFailed")); Bukkit.getPluginManager().disablePlugin(this); return; } logger.info(LocaleHandler.getString("Console.Database.Convert3.2")); // 3.1 -> 3.2+ try { // Add command column if (!((SQLDatabaseHandler) CouponCodes.getDatabaseHandler()).getConnection().getMetaData() .getColumns(null, null, "couponcodes", "command").next()) ((SQLDatabaseHandler) CouponCodes.getDatabaseHandler()) .query("ALTER TABLE couponcodes ADD COLUMN command VARCHAR(255)"); // IDs -> Names ResultSet rs = ((SQLDatabaseHandler) CouponCodes.getDatabaseHandler()) .query("SELECT name,ids FROM couponcodes WHERE ctype='Item'"); if (rs != null) { while (rs.next()) { HashMap<String, String> replacements = new HashMap<>(); for (String sp : rs.getString("ids").split(",")) { if (StringUtils.isNumeric(sp.split(":")[0])) { @SuppressWarnings("deprecation") // Warning ignored. This is a compatibility patch from old versions. String name = Material.getMaterial(Integer.parseInt(sp.split(":")[0])).toString(); String oldid = sp.split(":")[0]; replacements.put(name, oldid); } } String itemlist = rs.getString("ids"); for (String key : replacements.keySet()) { itemlist = itemlist.replace(replacements.get(key), key); logger.info("ID: " + replacements.get(key) + " changed to: " + key); logger.info( LocaleHandler.getString("Console.Database.Changed", replacements.get(key), key)); } ((SQLDatabaseHandler) CouponCodes.getDatabaseHandler()).query("UPDATE couponcodes SET ids='" + itemlist + "' WHERE name='" + rs.getString("name") + "'"); } } } catch (SQLException e) { logger.severe(LocaleHandler.getString("Console.Database.FailedUpdate")); e.printStackTrace(); Bukkit.getPluginManager().disablePlugin(this); return; } logger.info("Database updating successful"); // Vault if (!setupVault()) { logger.info(LocaleHandler.getString("Console.Vault.Disabled")); } else { logger.info(LocaleHandler.getString("Console.Vault.Enabled")); CouponCodes.setEconomyHandler(new VaultEconomyHandler(econ)); } // Events getServer().getPluginManager().registerEvents(new BukkitListener(this), this); // Permissions if (getServer().getPluginManager().getPlugin("Vault") != null) { CouponCodes.setPermissionHandler(new VaultPermissionHandler()); } else { CouponCodes.setPermissionHandler(new SuperPermsPermissionHandler()); } // Timer if (CouponCodes.getConfigHandler().getUseThread()) { getServer().getScheduler().scheduleSyncRepeatingTask(this, new BukkitCouponTimer(), 200L, 200L); } // Metrics if (CouponCodes.getConfigHandler().getUseMetrics()) { try { Metrics metrics = new Metrics(this); CouponCodes.getModTransformer().scheduleRunnable(new CustomDataSender(metrics)); metrics.start(); } catch (IOException ignored) { } } //Updater if (CouponCodes.getConfigHandler().getAutoUpdate()) { new Updater(this, 53833, this.getFile(), Updater.UpdateType.DEFAULT, false); } }
From source file:net.hydromatic.foodbench.Main.java
/** Does the work. */ private void run(String jdbcUrl, String catalog, String driverClassName) throws IOException, SQLException, ClassNotFoundException { URL url = FoodMartQuery.class.getResource("/queries.json"); InputStream inputStream = url.openStream(); ObjectMapper mapper = new ObjectMapper(); Map values = mapper.readValue(inputStream, Map.class); //noinspection unchecked List<Map<String, Object>> tests = (List) values.get("queries"); if (driverClassName != null) { Class.forName(driverClassName); }/*from w ww . ja va2 s. c om*/ Connection connection = DriverManager.getConnection(jdbcUrl); if (catalog != null) { connection.setCatalog(catalog); } Statement statement = connection.createStatement(); for (Map<String, Object> test : tests) { int id = (Integer) test.get("id"); if (!idSet.contains(id)) { continue; } String sql = (String) test.get("sql"); if (jdbcUrl.startsWith("jdbc:mysql:")) { sql = sql.replace("\"", "`"); sql = sql.replace(" NULLS FIRST", ""); sql = sql.replace(" NULLS LAST", ""); if (sql.contains("VALUES ")) { System.out.println("query id: " + id + " sql: " + sql + " skipped"); continue; } } if (jdbcUrl.startsWith("jdbc:optiq:")) { sql = sql.replace("RTRIM(", "TRIM(TRAILING ' ' FROM "); } final AtomicLong tPrepare = new AtomicLong(0); Hook.Closeable hook = Hook.JAVA_PLAN.add(new Function1<Object, Object>() { public Object apply(Object a0) { tPrepare.set(System.nanoTime()); return null; } }); try { final long t0 = System.nanoTime(); ResultSet resultSet = statement.executeQuery(sql); int n = 0; while (resultSet.next()) { ++n; } resultSet.close(); final long tEnd = System.nanoTime(); final long nanos = tEnd - t0; final long prepare = tPrepare.longValue() - t0; final long execute = tEnd - tPrepare.longValue(); System.out.println("query id: " + id + " rows: " + n + " nanos: " + NF.format(nanos) + " prepare: " + NF.format(prepare) + " execute: " + NF.format(execute) + " prepare%: " + ((float) prepare / (float) nanos * 100f)); } catch (SQLException e) { System.out.println("query id: " + id + " sql: " + sql + " error: " + e.getMessage()); if (verbose) { e.printStackTrace(); } } finally { hook.close(); } } statement.close(); connection.close(); }
From source file:com.abixen.platform.service.businessintelligence.multivisualization.service.impl.AbstractDatabaseService.java
public List<String> getColumns(Connection connection, String tableName) { List<String> columns = new ArrayList<>(); try {/*from w ww. j av a2 s . c om*/ ResultSetMetaData rsmd = getDatabaseMetaData(connection, tableName); int columnCount = rsmd.getColumnCount(); IntStream.range(1, columnCount + 1).forEach(i -> { try { columns.add(rsmd.getColumnName(i)); } catch (SQLException e) { e.printStackTrace(); } }); } catch (SQLException e) { e.printStackTrace(); } return columns; }
From source file:com.cloudera.sqoop.manager.DirectMySQLExportTest.java
/** * Test an authenticated export using mysqlimport. *//*from w w w.java 2 s . c o m*/ public void testAuthExport() throws IOException, SQLException { SqoopOptions options = new SqoopOptions(MySQLAuthTest.AUTH_CONNECT_STRING, getTableName()); options.setUsername(MySQLAuthTest.AUTH_TEST_USER); options.setPassword(MySQLAuthTest.AUTH_TEST_PASS); manager = new DirectMySQLManager(options); Connection connection = null; Statement st = null; String tableName = getTableName(); try { connection = manager.getConnection(); connection.setAutoCommit(false); st = connection.createStatement(); // create a target database table. st.executeUpdate("DROP TABLE IF EXISTS " + tableName); st.executeUpdate("CREATE TABLE " + tableName + " (" + "id INT NOT NULL PRIMARY KEY, " + "msg VARCHAR(24) NOT NULL)"); connection.commit(); // Write a file containing a record to export. Path tablePath = getTablePath(); Path filePath = new Path(tablePath, "datafile"); Configuration conf = new Configuration(); conf.set("fs.default.name", "file:///"); FileSystem fs = FileSystem.get(conf); fs.mkdirs(tablePath); OutputStream os = fs.create(filePath); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(os)); w.write(getRecordLine(0)); w.write(getRecordLine(1)); w.write(getRecordLine(2)); w.close(); os.close(); // run the export and verify that the results are good. runExport(getArgv(true, 10, 10, "--username", MySQLAuthTest.AUTH_TEST_USER, "--password", MySQLAuthTest.AUTH_TEST_PASS, "--connect", MySQLAuthTest.AUTH_CONNECT_STRING)); verifyExport(3, connection); } catch (SQLException sqlE) { LOG.error("Encountered SQL Exception: " + sqlE); sqlE.printStackTrace(); fail("SQLException when accessing target table. " + sqlE); } finally { try { if (null != st) { st.close(); } if (null != connection) { connection.close(); } } catch (SQLException sqlE) { LOG.warn("Got SQLException when closing connection: " + sqlE); } } }
From source file:com.anyuan.thomweboss.persistence.jdbcimpl.user.UserDaoJdbcImpl.java
@Override public boolean save(User entity) { Connection conn = getConnection(); boolean result = false; String userSql = "insert into t_user (f_username, f_nickname, f_loginname, f_password, " + "f_birthday, f_gender, f_createtime, f_logintime, f_roleid, f_contactid, " + "f_description) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try {// w w w . j a v a 2s. c om conn.setAutoCommit(false); Contact contact = entity.getContact(); Address address = contact.getAddress(); saveAddress(conn, address); // address id not modify, Addressgettersetter Phone phone = contact.getPhone(); savePhone(conn, phone); saveContact(conn, contact); PreparedStatement preState = conn.prepareStatement(userSql); preState.setObject(1, entity.getUsername()); preState.setString(2, entity.getNickname()); preState.setString(3, entity.getLoginname()); preState.setString(4, entity.getPassword()); preState.setObject(5, entity.getBirthday()); preState.setObject(6, entity.getGender()); preState.setObject(7, entity.getCreatetime()); preState.setObject(8, entity.getLogintime()); // ? preState.setObject(9, null); preState.setObject(10, entity.getContact().getId()); preState.setObject(11, entity.getDescription()); result = preState.execute(); conn.commit(); } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return result; }
From source file:edu.byu.wso2.apim.extensions.CheckActorPermissions.java
private List<Service> getServices() { if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("Start : getServices"); }/* w w w . j ava 2 s . c o m*/ List<Service> serviceList = new ArrayList<Service>(); Connection con = null; PreparedStatement statement = null; ResultSet resultSet = null; String query = "select web_service_id, url_pattern from common.web_service order by url_pattern"; if (synLog.isTraceOrDebugEnabled()) synLog.traceOrDebug("getServices: retrieving web services with url patterns from common.web_service"); try { con = proDs.getConnection(); if (synLog.isTraceOrDebugEnabled()) synLog.traceOrDebug("connection acquired. creating statement and executing query"); statement = con.prepareStatement(query); resultSet = statement.executeQuery(); while (resultSet.next()) { serviceList .add(new Service(resultSet.getLong("web_service_id"), resultSet.getString("url_pattern"))); } } catch (SQLException e) { e.printStackTrace(); } finally { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { /* ignored */ } } if (statement != null) { try { statement.close(); } catch (SQLException e) { /* ignored */ } } if (con != null) { try { con.close(); } catch (SQLException e) { /* ignored */ } } } if (synLog.isTraceOrDebugEnabled()) { synLog.traceOrDebug("getService: ending"); } return serviceList; }