List of usage examples for java.sql DriverManager getConnection
private static Connection getConnection(String url, java.util.Properties info, Class<?> caller) throws SQLException
From source file:TypeInfo.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/*w ww. j a v a 2s.com*/ DatabaseMetaData dbmd; 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"); dbmd = con.getMetaData(); ResultSet rs = dbmd.getTypeInfo(); while (rs.next()) { String typeName = rs.getString("TYPE_NAME"); short dataType = rs.getShort("DATA_TYPE"); String createParams = rs.getString("CREATE_PARAMS"); int nullable = rs.getInt("NULLABLE"); boolean caseSensitive = rs.getBoolean("CASE_SENSITIVE"); System.out.println("DBMS type " + typeName + ":"); System.out.println(" java.sql.Types: " + dataType); System.out.print(" parameters used to create: "); System.out.println(createParams); System.out.println(" nullable?: " + nullable); System.out.print(" case sensitive?: "); System.out.println(caseSensitive); System.out.println(""); } con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:InsertRows.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/*from w ww . j a v a 2s. 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(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); uprs.moveToInsertRow(); uprs.updateString("COF_NAME", "Kona"); uprs.updateInt("SUP_ID", 150); uprs.updateFloat("PRICE", 10.99f); uprs.updateInt("SALES", 0); uprs.updateInt("TOTAL", 0); uprs.insertRow(); uprs.updateString("COF_NAME", "Kona_Decaf"); uprs.updateInt("SUP_ID", 150); uprs.updateFloat("PRICE", 11.99f); uprs.updateInt("SALES", 0); uprs.updateInt("TOTAL", 0); uprs.insertRow(); uprs.beforeFirst(); System.out.println("Table COFFEES after insertion:"); while (uprs.next()) { String name = uprs.getString("COF_NAME"); int id = uprs.getInt("SUP_ID"); float price = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int total = uprs.getInt("TOTAL"); System.out.print(name + " " + id + " " + price); System.out.println(" " + sales + " " + total); } uprs.close(); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:com.l2jserver.model.template.SkillTemplateConverter.java
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException { Class.forName("com.mysql.jdbc.Driver"); final File target = new File("data/templates"); final JAXBContext c = JAXBContext.newInstance(SkillTemplate.class, LegacySkillList.class); final Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD); System.out.println("Generating template XML files..."); c.generateSchema(new SchemaOutputResolver() { @Override/* www .jav a2s. co m*/ public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { return new StreamResult(new File(target, suggestedFileName)); } }); try { final Unmarshaller u = c.createUnmarshaller(); final Marshaller m = c.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "skill"); m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "skill ../skill.xsd"); Collection<File> files = FileUtils.listFiles(new File(LEGACY_SKILL_FOLDER), new String[] { "xml" }, true); for (final File legacyFile : files) { LegacySkillList list = (LegacySkillList) u.unmarshal(legacyFile); for (final LegacySkill legacySkill : list.skills) { SkillTemplate t = fillSkill(legacySkill); final File file = new File(target, "skill/" + t.id.getID() + (t.getName() != null ? "-" + camelCase(t.getName()) : "") + ".xml"); templates.add(t); try { m.marshal(t, getXMLSerializer(new FileOutputStream(file))); } catch (MarshalException e) { System.err.println( "Could not generate XML template file for " + t.getName() + " - " + t.getID()); file.delete(); } } } System.out.println("Generated " + templates.size() + " templates"); System.gc(); System.out.println("Free: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().freeMemory())); System.out.println("Total: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().totalMemory())); System.out.println("Used: " + FileUtils.byteCountToDisplaySize( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())); System.out.println("Max: " + FileUtils.byteCountToDisplaySize(Runtime.getRuntime().maxMemory())); } finally { conn.close(); } }
From source file:ExecuteSQL.java
public static void main(String[] args) { Connection conn = null; // Our JDBC connection to the database server try {// ww w. j a va 2 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:SetSavepoint.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; try {// w w w. j a v a 2 s .c om Class.forName("myDriver.className"); } catch (java.lang.ClassNotFoundException e) { System.err.print("ClassNotFoundException: "); System.err.println(e.getMessage()); } try { Connection con = DriverManager.getConnection(url, "myLogin", "myPassword"); con.setAutoCommit(false); String query = "SELECT COF_NAME, PRICE FROM COFFEES " + "WHERE TOTAL > ?"; String update = "UPDATE COFFEES SET PRICE = ? " + "WHERE COF_NAME = ?"; PreparedStatement getPrice = con.prepareStatement(query); PreparedStatement updatePrice = con.prepareStatement(update); getPrice.setInt(1, 7000); ResultSet rs = getPrice.executeQuery(); Savepoint save1 = con.setSavepoint(); while (rs.next()) { String cof = rs.getString("COF_NAME"); float oldPrice = rs.getFloat("PRICE"); float newPrice = oldPrice + (oldPrice * .05f); updatePrice.setFloat(1, newPrice); updatePrice.setString(2, cof); updatePrice.executeUpdate(); System.out.println("New price of " + cof + " is " + newPrice); if (newPrice > 11.99) { con.rollback(save1); } } getPrice = con.prepareStatement(query); updatePrice = con.prepareStatement(update); getPrice.setInt(1, 8000); rs = getPrice.executeQuery(); System.out.println(); Savepoint save2 = con.setSavepoint(); while (rs.next()) { String cof = rs.getString("COF_NAME"); float oldPrice = rs.getFloat("PRICE"); float newPrice = oldPrice + (oldPrice * .05f); updatePrice.setFloat(1, newPrice); updatePrice.setString(2, cof); updatePrice.executeUpdate(); System.out.println("New price of " + cof + " is " + newPrice); if (newPrice > 11.99) { con.rollback(save2); } } con.commit(); Statement stmt = con.createStatement(); rs = stmt.executeQuery("SELECT COF_NAME, " + "PRICE FROM COFFEES"); System.out.println(); while (rs.next()) { String name = rs.getString("COF_NAME"); float price = rs.getFloat("PRICE"); System.out.println("Current price of " + name + " is " + price); } con.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:InsertSuppliers.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/*from w w w . j av a 2s . co m*/ Statement stmt; String query = "select SUP_NAME, SUP_ID from SUPPLIERS"; 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(); stmt.executeUpdate("insert into SUPPLIERS " + "values(49, 'Superior Coffee', '1 Party Place', " + "'Mendocino', 'CA', '95460')"); stmt.executeUpdate("insert into SUPPLIERS " + "values(101, 'Acme, Inc.', '99 Market Street', " + "'Groundsville', 'CA', '95199')"); stmt.executeUpdate("insert into SUPPLIERS " + "values(150, 'The High Ground', '100 Coffee Lane', " + "'Meadows', 'CA', '93966')"); ResultSet rs = stmt.executeQuery(query); System.out.println("Suppliers and their ID Numbers:"); while (rs.next()) { String s = rs.getString("SUP_NAME"); int n = rs.getInt("SUP_ID"); System.out.println(s + " " + n); } stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:InsertCoffees.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;//from w ww. ja v a 2 s . com Statement stmt; String query = "select COF_NAME, PRICE from COFFEES"; 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(); stmt.executeUpdate("insert into COFFEES " + "values('Colombian', 00101, 7.99, 0, 0)"); stmt.executeUpdate("insert into COFFEES " + "values('French_Roast', 00049, 8.99, 0, 0)"); stmt.executeUpdate("insert into COFFEES " + "values('Espresso', 00150, 9.99, 0, 0)"); stmt.executeUpdate("insert into COFFEES " + "values('Colombian_Decaf', 00101, 8.99, 0, 0)"); stmt.executeUpdate("insert into COFFEES " + "values('French_Roast_Decaf', 00049, 9.99, 0, 0)"); ResultSet rs = stmt.executeQuery(query); System.out.println("Coffee Break Coffees and Prices:"); while (rs.next()) { String s = rs.getString("COF_NAME"); float f = rs.getFloat("PRICE"); System.out.println(s + " " + f); } stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:PrintColumns.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;// w ww . j a v a 2 s. c om String query = "select * from COFFEES"; 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(); ResultSet rs = stmt.executeQuery(query); ResultSetMetaData rsmd = rs.getMetaData(); PrintColumnTypes.printColTypes(rsmd); System.out.println(""); int numberOfColumns = rsmd.getColumnCount(); for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) System.out.print(", "); String columnName = rsmd.getColumnName(i); System.out.print(columnName); } System.out.println(""); while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { if (i > 1) System.out.print(", "); String columnValue = rs.getString(i); System.out.print(columnValue); } System.out.println(""); } stmt.close(); con.close(); } catch (SQLException ex) { System.err.print("SQLException: "); System.err.println(ex.getMessage()); } }
From source file:InsertRow.java
public static void main(String args[]) { String url = "jdbc:mySubprotocol:myDataSource"; Connection con;/* ww w. j av a 2s . c o m*/ Statement stmt; String query = "select COF_NAME, PRICE from COFFEES"; 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(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES"); uprs.moveToInsertRow(); uprs.updateString("COF_NAME", "Kona"); uprs.updateInt("SUP_ID", 150); uprs.updateFloat("PRICE", 10.99f); uprs.updateInt("SALES", 0); uprs.updateInt("TOTAL", 0); uprs.insertRow(); uprs.beforeFirst(); System.out.println("Table COFFEES after insertion:"); while (uprs.next()) { String s = uprs.getString("COF_NAME"); int sup = uprs.getInt("SUP_ID"); float f = uprs.getFloat("PRICE"); int sales = uprs.getInt("SALES"); int t = uprs.getInt("TOTAL"); System.out.print(s + " " + sup + " " + f + " "); System.out.println(sales + " " + t); } uprs.close(); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:Connect.java
public static void main(String[] av) { String dbURL = "jdbc:odbc:Companies"; try {//from w ww. j a v a 2s . co m // Load the jdbc-odbc bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Enable logging DriverManager.setLogWriter(new PrintWriter((System.err))); System.out.println("Getting Connection"); Connection conn = DriverManager.getConnection(dbURL, "ian", ""); // user, // passwd // If a SQLWarning object is available, print its // warning(s). There may be multiple warnings chained. SQLWarning warn = conn.getWarnings(); while (warn != null) { System.out.println("SQLState: " + warn.getSQLState()); System.out.println("Message: " + warn.getMessage()); System.out.println("Vendor: " + warn.getErrorCode()); System.out.println(""); warn = warn.getNextWarning(); } // Do something with the connection here... conn.close(); // All done with that DB connection } catch (ClassNotFoundException e) { System.out.println("Can't load driver " + e); } catch (SQLException e) { System.out.println("Database access failed " + e); } }