List of usage examples for java.sql SQLException getMessage
public String getMessage()
From source file:Main.java
public static void main(String[] args) { Connection conn = null;/*from ww w. java 2s. co m*/ Statement stmt = null; ResultSet rs = null; try { String driver = "oracle.jdbc.driver.OracleDriver"; Class.forName(driver).newInstance(); System.out.println("Connecting to database..."); String jdbcUrl = "jdbc:oracle:thin:@localhost:1521:ORCL"; conn = DriverManager.getConnection(jdbcUrl, "yourName", "mypwd"); stmt = conn.createStatement(); try { rs = stmt.executeQuery("Select * from no_table_exisits"); } catch (SQLException seRs) { String exMsg = "Message from MySQL Database"; String exSqlState = "Exception"; SQLException mySqlEx = new SQLException(exMsg, exSqlState); seRs.setNextException(mySqlEx); throw seRs; } } catch (SQLException se) { int count = 1; while (se != null) { System.out.println("SQLException " + count); System.out.println("Code: " + se.getErrorCode()); System.out.println("SqlState: " + se.getSQLState()); System.out.println("Error Message: " + se.getMessage()); se = se.getNextException(); count++; } } catch (Exception e) { e.printStackTrace(); } }
From source file:jfutbol.com.jfutbol.GcmSender.java
public static void main(String[] args) { log.info("GCM - Sender running"); do {/* w ww. ja v a2s . c o m*/ Connection conn = null; Connection conn2 = null; Statement stmt = null; Statement stmt2 = null; try { // STEP 2: Register JDBC driver Class.forName(JDBC_DRIVER); // STEP 3: Open a connection // System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); conn2 = DriverManager.getConnection(DB_URL, USER, PASS); // STEP 4: Execute a query // System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT userId FROM notifications WHERE sentByGCM=0 GROUP BY userId"; ResultSet rs = stmt.executeQuery(sql); // STEP 5: Extract data from result set while (rs.next()) { log.info("Notification found"); int userId = rs.getInt("userId"); stmt2 = conn2.createStatement(); String sql2; sql2 = "SELECT COUNT(id) notificationCounter FROM notifications WHERE status=0 AND userId=" + userId; ResultSet rs2 = stmt2.executeQuery(sql2); int notificationCounter = rs2.getInt("notificationCounter"); rs2.close(); stmt2.close(); // Retrieve by column name // Display values // System.out.print("userId: " + userId); // System.out.print(", notificationCounter: " + // notificationCounter); SendNotification(userId, notificationCounter); } // STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close(); conn2.close(); } catch (SQLException se) { // Handle errors for JDBC log.error(se.getMessage()); se.printStackTrace(); } catch (Exception e) { // Handle errors for Class.forName log.error(e.getMessage()); e.printStackTrace(); } finally { // finally block used to close resources try { if (stmt != null) stmt.close(); } catch (SQLException se2) { log.error(se2.getMessage()); } // nothing we can do try { if (conn != null) conn.close(); } catch (SQLException se) { log.error(se.getMessage()); se.printStackTrace(); } // end finally try } // end try try { Thread.sleep(1000); } catch (InterruptedException e) { log.error(e.getMessage()); e.printStackTrace(); } } while (1 != 0); }
From source file:ExecuteSQL.java
public static void main(String[] args) { Connection conn = null; // Our JDBC connection to the database server try {/*from w ww. j a v a2 s .c o m*/ String driver = null, url = null, user = "", password = ""; // Parse all the command-line arguments for (int n = 0; n < args.length; n++) { if (args[n].equals("-d")) driver = args[++n]; else if (args[n].equals("-u")) user = args[++n]; else if (args[n].equals("-p")) password = args[++n]; else if (url == null) url = args[n]; else throw new IllegalArgumentException("Unknown argument."); } // The only required argument is the database URL. if (url == null) throw new IllegalArgumentException("No database specified"); // If the user specified the classname for the DB driver, load // that class dynamically. This gives the driver the opportunity // to register itself with the DriverManager. if (driver != null) Class.forName(driver); // Now open a connection the specified database, using the // user-specified username and password, if any. The driver // manager will try all of the DB drivers it knows about to try to // parse the URL and connect to the DB server. conn = DriverManager.getConnection(url, user, password); // Now create the statement object we'll use to talk to the DB Statement s = conn.createStatement(); // Get a stream to read from the console BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // Loop forever, reading the user's queries and executing them while (true) { System.out.print("sql> "); // prompt the user System.out.flush(); // make the prompt appear now. String sql = in.readLine(); // get a line of input from user // Quit when the user types "quit". if ((sql == null) || sql.equals("quit")) break; // Ignore blank lines if (sql.length() == 0) continue; // Now, execute the user's line of SQL and display results. try { // We don't know if this is a query or some kind of // update, so we use execute() instead of executeQuery() // or executeUpdate() If the return value is true, it was // a query, else an update. boolean status = s.execute(sql); // Some complex SQL queries can return more than one set // of results, so loop until there are no more results do { if (status) { // it was a query and returns a ResultSet ResultSet rs = s.getResultSet(); // Get results printResultsTable(rs, System.out); // Display them } else { // If the SQL command that was executed was some // kind of update rather than a query, then it // doesn't return a ResultSet. Instead, we just // print the number of rows that were affected. int numUpdates = s.getUpdateCount(); System.out.println("Ok. " + numUpdates + " rows affected."); } // Now go see if there are even more results, and // continue the results display loop if there are. status = s.getMoreResults(); } while (status || s.getUpdateCount() != -1); } // If a SQLException is thrown, display an error message. // Note that SQLExceptions can have a general message and a // DB-specific message returned by getSQLState() catch (SQLException e) { System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState()); } // Each time through this loop, check to see if there were any // warnings. Note that there can be a whole chain of warnings. finally { // print out any warnings that occurred SQLWarning w; for (w = conn.getWarnings(); w != null; w = w.getNextWarning()) System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState()); } } } // Handle exceptions that occur during argument parsing, database // connection setup, etc. For SQLExceptions, print the details. catch (Exception e) { System.err.println(e); if (e instanceof SQLException) System.err.println("SQL State: " + ((SQLException) e).getSQLState()); System.err.println( "Usage: java ExecuteSQL [-d <driver>] " + "[-u <user>] [-p <password>] <database URL>"); } // Be sure to always close the database connection when we exit, // whether we exit because the user types 'quit' or because of an // exception thrown while setting things up. Closing this connection // also implicitly closes any open statements and result sets // associated with it. finally { try { conn.close(); } catch (Exception e) { } } }
From source file:de.tudarmstadt.ukp.csniper.resbuild.EvaluationItemFixer2.java
public static void main(String[] args) { connect(HOST, DATABASE, USER, PASSWORD); Map<Integer, String> items = new HashMap<Integer, String>(); Map<Integer, String> failed = new HashMap<Integer, String>(); // fetch coveredTexts of dubious items and clean it PreparedStatement select = null; PreparedStatement update = null; try {// w ww . ja va 2 s. c o m StringBuilder selectQuery = new StringBuilder(); selectQuery.append("SELECT * FROM cachedparse WHERE pennTree = 'ERROR' OR pennTree = ''"); select = connection.prepareStatement(selectQuery.toString()); log.info("Running query [" + selectQuery.toString() + "]."); ResultSet rs = select.executeQuery(); // CSVWriter writer; String text; JCas jcas = JCasFactory.createJCas(); String updateQuery = "UPDATE CachedParse SET pennTree = ? WHERE collectionId = ? AND documentId = ? AND beginOffset = ? AND endOffset = ?"; update = connection.prepareStatement(updateQuery); // File base = new File(""); AnalysisEngine sentences = createEngine(DummySentenceSplitter.class); AnalysisEngine tokenizer = createEngine(StanfordSegmenter.class, StanfordSegmenter.PARAM_CREATE_SENTENCES, false, StanfordSegmenter.PARAM_CREATE_TOKENS, true); AnalysisEngine parser = createEngine(StanfordParser.class, StanfordParser.PARAM_WRITE_CONSTITUENT, true, // StanfordParser.PARAM_CREATE_DEPENDENCY_TAGS, true, StanfordParser.PARAM_WRITE_PENN_TREE, true, StanfordParser.PARAM_LANGUAGE, "en", StanfordParser.PARAM_VARIANT, "factored"); while (rs.next()) { String collectionId = rs.getString("collectionId"); String documentId = rs.getString("documentId"); int beginOffset = rs.getInt("beginOffset"); int endOffset = rs.getInt("endOffset"); text = retrieveCoveredText(collectionId, documentId, beginOffset, endOffset); jcas.setDocumentText(text); jcas.setDocumentLanguage("en"); sentences.process(jcas); tokenizer.process(jcas); parser.process(jcas); // writer = new CSVWriter(new FileWriter(new File(base, documentId + ".csv")); System.out.println("Updating " + text); for (PennTree p : JCasUtil.select(jcas, PennTree.class)) { String tree = StringUtils.normalizeSpace(p.getPennTree()); update.setString(1, tree); update.setString(2, collectionId); update.setString(3, documentId); update.setInt(4, beginOffset); update.setInt(5, endOffset); update.executeUpdate(); System.out.println("with tree " + tree); break; } jcas.reset(); } } catch (SQLException e) { log.error("Exception while selecting: " + e.getMessage()); } catch (UIMAException e) { e.printStackTrace(); } finally { closeQuietly(select); closeQuietly(update); } // write logs // BufferedWriter bwf = null; // BufferedWriter bws = null; // try { // bwf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File( // LOG_FAILED)), "UTF-8")); // for (Entry<Integer, String> e : failed.entrySet()) { // bwf.write(e.getKey() + " - " + e.getValue() + "\n"); // } // // bws = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File( // LOG_SUCCESSFUL)), "UTF-8")); // for (Entry<Integer, String> e : items.entrySet()) { // bws.write(e.getKey() + " - " + e.getValue() + "\n"); // } // } // catch (IOException e) { // log.error("Got an IOException while writing the log files."); // } // finally { // IOUtils.closeQuietly(bwf); // IOUtils.closeQuietly(bws); // } log.info("Texts for [" + items.size() + "] items need to be cleaned up."); // update the dubious items with the cleaned coveredText // PreparedStatement update = null; // try { // String updateQuery = "UPDATE EvaluationItem SET coveredText = ? WHERE id = ?"; // // update = connection.prepareStatement(updateQuery); // int i = 0; // for (Entry<Integer, String> e : items.entrySet()) { // int id = e.getKey(); // String coveredText = e.getValue(); // // // update item in database // update.setString(1, coveredText); // update.setInt(2, id); // update.executeUpdate(); // log.debug("Updating " + id + " with [" + coveredText + "]"); // // // show percentage of updated items // i++; // int part = (int) Math.ceil((double) items.size() / 100); // if (i % part == 0) { // log.info(i / part + "% finished (" + i + "/" + items.size() + ")."); // } // } // } // catch (SQLException e) { // log.error("Exception while updating: " + e.getMessage()); // } // finally { // closeQuietly(update); // } closeQuietly(connection); }
From source file:CreateNewType.java
public static void main(String[] args) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/*from ww w . j a va 2 s . c o m*/ Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); String typeToCreate = null; String prompt = "Enter 's' to create a structured type " + "or 'd' to create a distinct type\n" + "and hit Return: "; do { typeToCreate = getInput(prompt) + " "; typeToCreate = typeToCreate.toLowerCase().substring(0, 1); } while (!(typeToCreate.equals("s") || typeToCreate.equals("d"))); Vector dataTypes = getDataTypes(con, typeToCreate); String typeName; String attributeName; String sqlType; prompt = "Enter the new type name and hit Return: "; typeName = getInput(prompt); String createTypeString = "create type " + typeName; if (typeToCreate.equals("d")) createTypeString += " as "; else createTypeString += " ("; String commaAndSpace = ", "; boolean firstTime = true; while (true) { System.out.println(""); prompt = "Enter an attribute name " + "(or nothing when finished) \nand hit Return: "; attributeName = getInput(prompt); if (firstTime) { if (attributeName.length() == 0) { System.out.print("Need at least one attribute;"); System.out.println(" please try again"); continue; } else { createTypeString += attributeName + " "; firstTime = false; } } else if (attributeName.length() == 0) { break; } else { createTypeString += commaAndSpace + attributeName + " "; } String localTypeName = null; String paramString = ""; while (true) { System.out.println(""); System.out.println("LIST OF TYPES YOU MAY USE: "); boolean firstPrinted = true; int length = 0; for (int i = 0; i < dataTypes.size(); i++) { DataType dataType = (DataType) dataTypes.get(i); if (!dataType.needsToBeSet()) { if (!firstPrinted) System.out.print(commaAndSpace); else firstPrinted = false; System.out.print(dataType.getSQLType()); length += dataType.getSQLType().length(); if (length > 50) { System.out.println(""); length = 0; firstPrinted = true; } } } System.out.println(""); int index; prompt = "Enter an attribute type " + "from the list and hit Return: "; sqlType = getInput(prompt); for (index = 0; index < dataTypes.size(); index++) { DataType dataType = (DataType) dataTypes.get(index); if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) { break; } } localTypeName = null; paramString = ""; if (index < dataTypes.size()) { // there was a match String params; DataType dataType = (DataType) dataTypes.get(index); params = dataType.getParams(); localTypeName = dataType.getLocalType(); if (params != null) { prompt = "Enter " + params + ": "; paramString = "(" + getInput(prompt) + ")"; } break; } else { // use the name as given prompt = "Are you sure? " + "Enter 'y' or 'n' and hit Return: "; String check = getInput(prompt) + " "; check = check.toLowerCase().substring(0, 1); if (check.equals("n")) continue; else { localTypeName = sqlType; break; } } } createTypeString += localTypeName + paramString; if (typeToCreate.equals("d")) break; } if (typeToCreate.equals("s")) createTypeString += ")"; System.out.println(""); System.out.print("Your CREATE TYPE statement as "); System.out.println("sent to your DBMS: "); System.out.println(createTypeString); System.out.println(""); stmt.executeUpdate(createTypeString); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:Main.java
public static void main(String[] args) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/* w w w . j a va 2 s . com*/ Statement stmt; try { Class.forName("myDriver.ClassName"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, "myLogin", "myPassword"); stmt = con.createStatement(); Vector dataTypes = getDataTypes(con); String tableName; String columnName; String sqlType; String prompt = "Enter the new table name and hit Return: "; tableName = getInput(prompt); String createTableString = "create table " + tableName + " ("; String commaAndSpace = ", "; boolean firstTime = true; while (true) { System.out.println(""); prompt = "Enter a column name " + "(or nothing when finished) \nand hit Return: "; columnName = getInput(prompt); if (firstTime) { if (columnName.length() == 0) { System.out.print("Need at least one column;"); System.out.println(" please try again"); continue; } else { createTableString += columnName + " "; firstTime = false; } } else if (columnName.length() == 0) { break; } else { createTableString += commaAndSpace + columnName + " "; } String localTypeName = null; String paramString = ""; while (true) { System.out.println(""); System.out.println("LIST OF TYPES YOU MAY USE: "); boolean firstPrinted = true; int length = 0; for (int i = 0; i < dataTypes.size(); i++) { DataType dataType = (DataType) dataTypes.get(i); if (!dataType.needsToBeSet()) { if (!firstPrinted) System.out.print(commaAndSpace); else firstPrinted = false; System.out.print(dataType.getSQLType()); length += dataType.getSQLType().length(); if (length > 50) { System.out.println(""); length = 0; firstPrinted = true; } } } System.out.println(""); int index; prompt = "Enter a column type " + "from the list and hit Return: "; sqlType = getInput(prompt); for (index = 0; index < dataTypes.size(); index++) { DataType dataType = (DataType) dataTypes.get(index); if (dataType.getSQLType().equalsIgnoreCase(sqlType) && !dataType.needsToBeSet()) { break; } } localTypeName = null; paramString = ""; if (index < dataTypes.size()) { // there was a match String params; DataType dataType = (DataType) dataTypes.get(index); params = dataType.getParams(); localTypeName = dataType.getLocalType(); if (params != null) { prompt = "Enter " + params + ": "; paramString = "(" + getInput(prompt) + ")"; } break; } else { // use the name as given prompt = "Are you sure? " + "Enter 'y' or 'n' and hit Return: "; String check = getInput(prompt) + " "; check = check.toLowerCase().substring(0, 1); if (check.equals("n")) continue; else { localTypeName = sqlType; break; } } } createTableString += localTypeName + paramString; } createTableString += ")"; System.out.println(""); System.out.print("Your CREATE TABLE statement as "); System.out.println("sent to your DBMS: "); System.out.println(createTableString); System.out.println(""); stmt.executeUpdate(createTableString); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:SimpleProgramToAccessOracleDatabase.java
public static void main(String[] args) throws SQLException { Connection conn = null; // connection object Statement stmt = null; // statement object ResultSet rs = null; // result set object try {//from w ww .j av a2 s. co m conn = getConnection(); // without Connection, can not do much // create a statement: This object will be used for executing // a static SQL statement and returning the results it produces. stmt = conn.createStatement(); // start a transaction conn.setAutoCommit(false); // create a table called cats_tricks stmt.executeUpdate("CREATE TABLE cats_tricks " + "(name VARCHAR2(30), trick VARCHAR2(30))"); // insert two new records to the cats_tricks table stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'r')"); stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'j')"); // commit the transaction conn.commit(); // set auto commit to true (from now on every single // statement will be treated as a single transaction conn.setAutoCommit(true); // get all of the the records from the cats_tricks table rs = stmt.executeQuery("SELECT name, trick FROM cats_tricks"); // iterate the result set and get one row at a time while (rs.next()) { String name = rs.getString(1); // 1st column in query String trick = rs.getString(2); // 2nd column in query System.out.println("name=" + name); System.out.println("trick=" + trick); System.out.println("=========="); } } catch (ClassNotFoundException ce) { // if the driver class not found, then we will be here System.out.println(ce.getMessage()); } catch (SQLException e) { // something went wrong, we are handling the exception here if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } System.out.println("--- SQLException caught ---"); // iterate and get all of the errors as much as possible. while (e != null) { System.out.println("Message : " + e.getMessage()); System.out.println("SQLState : " + e.getSQLState()); System.out.println("ErrorCode : " + e.getErrorCode()); System.out.println("---"); e = e.getNextException(); } } finally { // close db resources try { rs.close(); stmt.close(); conn.close(); } catch (Exception e) { } } }
From source file:ProxyAuthTest.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("Usage ProxyAuthTest <host> <port> <server_principal> <proxy_user> [testTab]"); System.exit(1);/*ww w .ja v a 2 s . c o m*/ } File currentResultFile = null; String[] beeLineArgs = {}; Class.forName(driverName); String host = args[0]; String port = args[1]; String serverPrincipal = args[2]; String proxyUser = args[3]; String url = null; if (args.length > 4) { tabName = args[4]; } generateData(); generateSQL(null); try { /* * Connect via kerberos and get delegation token */ url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; con = DriverManager.getConnection(url); System.out.println("Connected successfully to " + url); // get delegation token for the given proxy user String token = ((HiveConnection) con).getDelegationToken(proxyUser, serverPrincipal); if ("true".equals(System.getProperty("proxyAuth.debug", "false"))) { System.out.println("Got token: " + token); } con.close(); // so that beeline won't kill the JVM System.setProperty(BEELINE_EXIT, "true"); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar" }; System.out.println("Connection with kerberos, user/password via args, using input rediction"); BeeLine.mainWithInputRedirection(beeLineArgs, inpStream); compareResults(currentResultFile); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar", "-f", scriptFileName }; System.out.println("Connection with kerberos, user/password via args, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(url + " foo bar "); beeLineArgs = new String[] { "-u", url, "-f", scriptFileName }; System.out.println("Connection with kerberos, user/password via connect, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(url + " foo bar "); beeLineArgs = new String[] { "-u", url, "-f", scriptFileName }; System.out.println("Connection with kerberos, user/password via connect, using input redirect"); BeeLine.mainWithInputRedirection(beeLineArgs, inpStream); compareResults(currentResultFile); /* * Connect using the delegation token passed via configuration object */ System.out.println("Store token into ugi and try"); storeTokenInJobConf(token); url = "jdbc:hive2://" + host + ":" + port + "/default;auth=delegationToken"; con = DriverManager.getConnection(url); System.out.println("Connecting to " + url); runTest(); con.close(); // connect using token via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar", "-a", "delegationToken" }; System.out.println("Connection with token, user/password via args, using input redirection"); BeeLine.mainWithInputRedirection(beeLineArgs, inpStream); compareResults(currentResultFile); // connect using token via Beeline using script url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar", "-a", "delegationToken", "-f", scriptFileName }; System.out.println("Connection with token, user/password via args, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using token via Beeline using script url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(url + " foo bar "); beeLineArgs = new String[] { "-a", "delegationToken", "-f", scriptFileName }; System.out.println("Connection with token, user/password via connect, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using token via Beeline using script url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(url + " foo bar "); System.out.println("Connection with token, user/password via connect, using input script"); beeLineArgs = new String[] { "-f", scriptFileName, "-a", "delegationToken" }; BeeLine.main(beeLineArgs); compareResults(currentResultFile); /* * Connect via kerberos with trusted proxy user */ url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal + ";hive.server2.proxy.user=" + proxyUser; con = DriverManager.getConnection(url); System.out.println("Connected successfully to " + url); runTest(); ((HiveConnection) con).cancelDelegationToken(token); con.close(); } catch (SQLException e) { System.out.println("*** SQLException: " + e.getMessage() + " : " + e.getSQLState()); e.printStackTrace(); } /* verify the connection fails after canceling the token */ try { url = "jdbc:hive2://" + host + ":" + port + "/default;auth=delegationToken"; con = DriverManager.getConnection(url); throw new Exception("connection should have failed after token cancelation"); } catch (SQLException e) { // Expected to fail due to canceled token } }
From source file:de.tu_berlin.dima.oligos.Oligos.java
public static void main(String[] args) throws TypeNotSupportedException { BasicConfigurator.configure();/*from ww w . j ava 2s . c o m*/ // TODO create cmdline option for setting logger level Logger.getRootLogger().setLevel(Level.INFO); CommandLineInterface cli = new CommandLineInterface(args); try { // TODO hard exit if the parsing fails! // better catch exceptions and log them if (!cli.parse()) { System.exit(2); } Properties props = new Properties(); props.setProperty("user", cli.getUsername()); props.setProperty("password", cli.getPassword()); Connection connection = DriverManager.getConnection(cli.getConnectionString(), props); JdbcConnector jdbcConnector = new JdbcConnector(connection); MetaConnector metaConnector = null; Driver dbDriver = cli.dbDriver; switch (dbDriver.driverName) { case db2: LOGGER.trace("metaConnector = Db2MetaConnector"); metaConnector = new Db2MetaConnector(jdbcConnector); break; case oracle: metaConnector = new OracleMetaConnector(jdbcConnector); break; default: LOGGER.error("Unknown database driver. Supported drivers are: " + DriverName.values()); } // validating schema LOGGER.info("Validating input schema ..."); SparseSchema sparseSchema = cli.getInputSchema(); LOGGER.trace("User specified schema " + sparseSchema); DenseSchema inputSchema = DbUtils.populateSchema(sparseSchema, jdbcConnector, metaConnector); LOGGER.trace("Populated and validated schema " + inputSchema); // obtaining type information/ column meta data LOGGER.info("Retrieving column meta data ..."); Map<ColumnId, TypeInfo> columnTypes = Maps.newLinkedHashMap(); for (ColumnId columnId : inputSchema) { TypeInfo type = metaConnector.getColumnType(columnId); columnTypes.put(columnId, type); } // creating connectors and profilers LOGGER.info("Establashing database connection ..."); SchemaConnector schemaConnector = null; TableConnector tableConnector = null; switch (dbDriver.driverName) { case db2: schemaConnector = new Db2SchemaConnector(jdbcConnector); tableConnector = new Db2TableConnector(jdbcConnector); break; case oracle: schemaConnector = new OracleSchemaConnector(jdbcConnector); tableConnector = new OracleTableConnector(jdbcConnector); } Set<SchemaProfiler> profilers = Sets.newLinkedHashSet(); for (String schema : inputSchema.schemas()) { SchemaProfiler schemaProfiler = new SchemaProfiler(schema, schemaConnector); profilers.add(schemaProfiler); for (String table : inputSchema.tablesIn(schema)) { TableProfiler tableProfiler = new TableProfiler(schema, table, tableConnector); schemaProfiler.add(tableProfiler); for (String column : inputSchema.columnsIn(schema, table)) { ColumnId columnId = new ColumnId(schema, table, column); TypeInfo type = columnTypes.get(columnId); ColumnProfiler<?> columnProfiler = null; switch (dbDriver.driverName) { case db2: columnProfiler = getProfiler(schema, table, column, type, jdbcConnector, metaConnector); break; case oracle: columnProfiler = getProfilerOracle(schema, table, column, type, jdbcConnector, metaConnector); } tableProfiler.addColumnProfiler(columnProfiler); } } } // profiling statistical data LOGGER.info("Profiling schema ..."); Set<Schema> profiledSchemas = Sets.newLinkedHashSet(); for (SchemaProfiler schemaProfiler : profilers) { Schema profiledSchema = schemaProfiler.profile(); profiledSchemas.add(profiledSchema); } LOGGER.info("Generating generator specification ..."); File outputDir = cli.getOutputDirectory(); String generatorName = cli.getGeneratorName(); LOGGER.info("Writing generator specification ..."); for (Schema schema : profiledSchemas) { MyriadWriter writer = new MyriadWriter(schema, outputDir, generatorName); writer.write(); } LOGGER.info("Closing database connection ..."); connection.close(); } catch (SQLException e) { LOGGER.error(e.getLocalizedMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException e) { LOGGER.error(e.getLocalizedMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (ParseException e) { LOGGER.error(e.getMessage()); cli.printHelpMessage(); } }
From source file:com.mycompany.mavenproject4.NewMain.java
/** * @param args the command line arguments *///from ww w . j a v a 2 s. c o m public static void main(String[] args) { System.out.println("Enter your choice do you want to work with 1.postgre 2.Redis 3.Mongodb"); InputStreamReader IORdatabase = new InputStreamReader(System.in); BufferedReader BIOdatabase = new BufferedReader(IORdatabase); String databasechoice = null; try { databasechoice = BIOdatabase.readLine(); } catch (Exception E7) { System.out.println(E7.getMessage()); } // loading data from the CSV file CsvReader Employees = null; try { Employees = new CsvReader("CSVFile\\Employees.csv"); } catch (FileNotFoundException EB) { System.out.println(EB.getMessage()); } int ColumnCount = 3; int RowCount = 100; int iloop = 0; try { Employees = new CsvReader("CSVFile\\Employees.csv"); } catch (FileNotFoundException E) { System.out.println(E.getMessage()); } String[][] Dataarray = new String[RowCount][ColumnCount]; try { while (Employees.readRecord()) { String v; String[] x; v = Employees.getRawRecord(); x = v.split(","); for (int j = 0; j < ColumnCount; j++) { String value = null; int z = j; value = x[z]; try { Dataarray[iloop][j] = value; } catch (Exception E) { System.out.println(E.getMessage()); } // System.out.println(Dataarray[iloop][j]); } iloop = iloop + 1; } } catch (IOException Em) { System.out.println(Em.getMessage()); } Employees.close(); // connection to Database switch (databasechoice) { // postgre code goes here case "1": Connection Conn = null; Statement Stmt = null; URI dbUri = null; String choice = null; InputStreamReader objin = new InputStreamReader(System.in); BufferedReader objbuf = new BufferedReader(objin); try { Class.forName("org.postgresql.Driver"); } catch (Exception E1) { System.out.println(E1.getMessage()); } String username = "ldoiarosfrzrua"; String password = "HBkE_pJpK5mMIg3p2q1_odmEFX"; String dbUrl = "jdbc:postgresql://ec2-54-83-53-120.compute-1.amazonaws.com:5432/d6693oljh5cco4?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"; // now update data in the postgress Database // for(int i=0;i<RowCount;i++) // { // try // { // Conn= DriverManager.getConnection(dbUrl, username, password); // Stmt = Conn.createStatement(); // String Connection_String = "insert into EmployeeDistinct (name,jobtitle,department) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ')"; // Stmt.executeUpdate(Connection_String); // // } // catch(SQLException E4) // { // System.out.println(E4.getMessage()); // } // } // Quering with the Database System.out.println("1. Display Data "); System.out.println("2. Select data based on primary key"); System.out.println("3. Select data based on Other attributes e.g Name"); System.out.println("Enter your Choice "); try { choice = objbuf.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (choice) { case "1": try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from EmployeeDistinct;"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println("Employee ID: " + objRS.getInt("EmployeeID")); System.out.println("Employee Name: " + objRS.getString("Name")); System.out.println("Employee City: " + objRS.getString("Jobtitle")); System.out.println("Employee City: " + objRS.getString("Department")); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "2": System.out.println("Enter the Primary Key"); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); int key = 0; try { key = Integer.parseInt(objbufkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from EmployeeDistinct where EmployeeID=" + key + ";"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println("Employee Name: " + objRS.getString("Name")); System.out.println("Employee City: " + objRS.getString("Jobtitle")); System.out.println("Employee City: " + objRS.getString("Department")); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "3": String Name = null; System.out.println("Enter Name to find the record"); InputStreamReader objname = new InputStreamReader(System.in); BufferedReader objbufname = new BufferedReader(objname); try { Name = (objbufname.readLine()).toString(); } catch (IOException E) { System.out.println(E.getMessage()); } try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from EmployeeDistinct where Name=" + "'" + Name + "'" + ";"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println("Employee ID: " + objRS.getInt("EmployeeID")); System.out.println("Employee City: " + objRS.getString("Jobtitle")); System.out.println("Employee City: " + objRS.getString("Department")); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; } try { Conn.close(); } catch (SQLException E6) { System.out.println(E6.getMessage()); } break; // Redis code goes here case "2": int Length = 0; String ID = null; Length = 100; // Connection to Redis Jedis jedis = new Jedis("pub-redis-18017.us-east-1-4.6.ec2.redislabs.com", 18017); jedis.auth("7EFOisRwMu8zvhin"); System.out.println("Connected to Redis"); // Storing values in the database // System.out.println("Storing values in the Database might take a minute "); // for(int i=0;i<Length;i++) // { // Store data in redis // int j=i+1; // jedis.hset("Employe:" + j , "Name", Dataarray[i][0]); // jedis.hset("Employe:" + j , "Jobtitle ", Dataarray[i][1]); // jedis.hset("Employe:" + j , "Department", Dataarray[i][2]); // } System.out.println("Search by 1.primary key,2.Name 3.display first 20"); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); String interimChoice1 = null; try { interimChoice1 = objbufkey.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (interimChoice1) { case "1": System.out.print("Get details using the primary Key"); InputStreamReader IORKey = new InputStreamReader(System.in); BufferedReader BIORKey = new BufferedReader(IORKey); String ID1 = null; try { ID1 = BIORKey.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } Map<String, String> properties = jedis.hgetAll("Employe:" + Integer.parseInt(ID1)); for (Map.Entry<String, String> entry : properties.entrySet()) { System.out.println("Name:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Name")); System.out.println("Jobtitle:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Jobtitle")); System.out .println("Department:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Department")); } break; case "2": System.out.print("Get details using Department"); InputStreamReader IORName1 = new InputStreamReader(System.in); BufferedReader BIORName1 = new BufferedReader(IORName1); String ID2 = null; try { ID2 = BIORName1.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } for (int i = 0; i < 100; i++) { Map<String, String> properties3 = jedis.hgetAll("Employe:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { String value = entry.getValue(); if (entry.getValue().equals(ID2)) { System.out.println("Name:" + jedis.hget("Employee:" + i, "Name")); System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle")); System.out.println("Department:" + jedis.hget("Employee:" + i, "Department")); } } } //for (Map.Entry<String, String> entry : properties1.entrySet()) //{ //System.out.println(entry.getKey() + "---" + entry.getValue()); // } break; case "3": for (int i = 1; i < 21; i++) { Map<String, String> properties3 = jedis.hgetAll("Employe:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { // System.out.println(jedis.hget("Employee:" + i,"Name")); System.out.println("Name:" + jedis.hget("Employee:" + i, "Name")); System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle")); System.out.println("Department:" + jedis.hget("Employee:" + i, "Department")); } } break; } break; // mongo db code goes here case "3": MongoClient mongo = new MongoClient( new MongoClientURI("mongodb://root2:12345@ds055564.mongolab.com:55564/heroku_766dnj8c")); DB db; db = mongo.getDB("heroku_766dnj8c"); // storing values in the database // for(int i=0;i<100;i++) // { // BasicDBObject document = new BasicDBObject(); // document.put("_id", i+1); // document.put("Name", Dataarray[i][0]); // document.put("Jobtitle", Dataarray[i][1]); // document.put("Department", Dataarray[i][2]); // db.getCollection("EmployeeRaw").insert(document); // } System.out.println("Search by 1.primary key,2.Name 3.display first 20"); InputStreamReader objkey6 = new InputStreamReader(System.in); BufferedReader objbufkey6 = new BufferedReader(objkey6); String interimChoice = null; try { interimChoice = objbufkey6.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (interimChoice) { case "1": System.out.println("Enter the Primary Key"); InputStreamReader IORPkey = new InputStreamReader(System.in); BufferedReader BIORPkey = new BufferedReader(IORPkey); int Pkey = 0; try { Pkey = Integer.parseInt(BIORPkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery = new BasicDBObject(); inQuery.put("_id", Pkey); DBCursor cursor = db.getCollection("EmployeeRaw").find(inQuery); while (cursor.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor.next()); } break; case "2": System.out.println("Enter the Name to Search"); InputStreamReader objName = new InputStreamReader(System.in); BufferedReader objbufName = new BufferedReader(objName); String Name = null; try { Name = objbufName.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery1 = new BasicDBObject(); inQuery1.put("Name", Name); DBCursor cursor1 = db.getCollection("EmployeeRaw").find(inQuery1); while (cursor1.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor1.next()); } break; case "3": for (int i = 1; i < 21; i++) { BasicDBObject inQuerya = new BasicDBObject(); inQuerya.put("_id", i); DBCursor cursora = db.getCollection("EmployeeRaw").find(inQuerya); while (cursora.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursora.next()); } } break; } break; } }