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:Blobs.java
public static void main(String args[]) { if (args.length != 1) { System.err.println("Syntax: <java Blobs [driver] [url] " + "[uid] [pass] [file]"); return;/*from w w w .j ava 2 s . c o m*/ } try { Class.forName(args[0]).newInstance(); Connection con = DriverManager.getConnection(args[1], args[2], args[3]); File f = new File(args[4]); PreparedStatement stmt; if (!f.exists()) { // if the file does not exist // retrieve it from the database and write it to the named file ResultSet rs; stmt = con.prepareStatement("SELECT blobData " + "FROM BlobTest " + "WHERE fileName = ?"); stmt.setString(1, args[0]); rs = stmt.executeQuery(); if (!rs.next()) { System.out.println("No such file stored."); } else { Blob b = rs.getBlob(1); BufferedOutputStream os; os = new BufferedOutputStream(new FileOutputStream(f)); os.write(b.getBytes(0, (int) b.length()), 0, (int) b.length()); os.flush(); os.close(); } } else { // otherwise read it and save it to the database FileInputStream fis = new FileInputStream(f); byte[] tmp = new byte[1024]; byte[] data = null; int sz, len = 0; while ((sz = fis.read(tmp)) != -1) { if (data == null) { len = sz; data = tmp; } else { byte[] narr; int nlen; nlen = len + sz; narr = new byte[nlen]; System.arraycopy(data, 0, narr, 0, len); System.arraycopy(tmp, 0, narr, len, sz); data = narr; len = nlen; } } if (len != data.length) { byte[] narr = new byte[len]; System.arraycopy(data, 0, narr, 0, len); data = narr; } stmt = con.prepareStatement("INSERT INTO BlobTest(fileName, " + "blobData) VALUES(?, ?)"); stmt.setString(1, args[0]); stmt.setObject(2, data); stmt.executeUpdate(); f.delete(); } con.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName(DRIVER);//from w w w . j a v a2 s . co m Connection con = DriverManager.getConnection(CONNECTION_URL, USERNAME, PASSWORD); ResultSet rs = con.createStatement().executeQuery(QUERY); if (rs != null) { System.out.println("Column Type\t\t Column Name"); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <= rsmd.getColumnCount(); i++) { System.out.println(rsmd.getColumnTypeName(i) + "\t\t\t" + rsmd.getColumnName(i)); } } }
From source file:Main.java
public static void main(String[] argv) throws Exception { Connection dbConnection = null; PreparedStatement preparedStatement = null; String createTableSQL = "CREATE TABLE Person(" + "USER_ID NUMBER(5) NOT NULL, " + "USERNAME VARCHAR(20) NOT NULL, " + "CREATED_BY VARCHAR(20) NOT NULL, " + "CREATED_DATE DATE NOT NULL, " + "PRIMARY KEY (USER_ID) " + ")"; Class.forName(DB_DRIVER);/*w w w .j ava2 s. c om*/ dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD); preparedStatement = dbConnection.prepareStatement(createTableSQL); System.out.println(createTableSQL); preparedStatement.executeUpdate(); preparedStatement.close(); dbConnection.close(); }
From source file:TestClassForNameNewInstanceApp.java
public static void main(String args[]) { try {//www . j a v a 2 s.com Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); } catch (ClassNotFoundException e) { System.out.println("Oops! Can't find class oracle.jdbc.driver.OracleDriver"); System.exit(1); } catch (IllegalAccessException e) { System.out.println("Uh Oh! You can't load oracle.jdbc.driver.OracleDriver"); System.exit(2); } catch (InstantiationException e) { System.out.println("Geez! Can't instantiate oracle.jdbc.driver.OracleDriver"); System.exit(3); } Connection conn = null; Statement stmt = null; ResultSet rset = null; try { conn = DriverManager.getConnection("jdbc:oracle:thin:@dssw2k01:1521:orcl", "scott", "tiger"); stmt = conn.createStatement(); rset = stmt.executeQuery("select 'Hello '||USER||'!' result from dual"); while (rset.next()) System.out.println(rset.getString(1)); rset.close(); rset = null; stmt.close(); stmt = null; conn.close(); conn = null; } catch (SQLException e) { System.out.println("Darn! A SQL error: " + e.getMessage()); } finally { if (rset != null) try { rset.close(); } catch (SQLException ignore) { } if (stmt != null) try { stmt.close(); } catch (SQLException ignore) { } if (conn != null) try { conn.close(); } catch (SQLException ignore) { } } }
From source file:com.insightaction.util.DataLoader.java
public static void main(String[] args) throws Exception { String userName = "root"; String password = ""; String url = "jdbc:mysql://localhost:3306/insightaction"; Connection conn = DriverManager.getConnection(url, userName, password); DSLContext create = DSL.using(conn, SQLDialect.MYSQL); truncateData(create);/*from w w w. j a va2 s . co m*/ loadToStaging(create); mapStoreData(create); mapProductData(create); mapStoreProductData(create); }
From source file:com.hangum.tadpole.engine.procedure.OracleProcedure.java
/** * @param args/*from w ww . ja v a2s .c om*/ */ public static void main(String[] args) { String strQuery = "CREATE OR REPLACE PROCEDURE procOneINOUTParameter(genericParam IN OUT VARCHAR2) " + " IS " + " BEGIN " + " genericParam := 'Hello World INOUT parameter ' || genericParam; " + " END;"; Connection conn = null; Statement stmt = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.32.128:1521:XE", "HR", "tadpole"); stmt = conn.createStatement(); int code = stmt.executeUpdate(strQuery); System.out.println("[result]" + code); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:Employee.java
public static void main(String[] args) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@myserver:1521:ORCL", "yourName", "mypwd"); Statement stmt = conn.createStatement(); Map map = conn.getTypeMap();/*from w w w . ja v a 2 s . com*/ map.put("EMP_DATA", Class.forName("Employee")); conn.setTypeMap(map); ResultSet rs = stmt.executeQuery("SELECT * from Emp"); Employee employee; while (rs.next()) { int empId = rs.getInt("EmpId"); employee = (Employee) rs.getObject("Emp_Info"); System.out.print("Employee Id: " + empId + ", SSN: " + employee.SSN); System.out.print(", Name: " + employee.FirstName + " " + employee.LastName); System.out.println( ", Yearly Salary: $" + employee.Salary + " Monthly Salary: " + employee.calcMonthlySalary()); } conn.close(); }
From source file:io.apiman.tools.jdbc.ApimanJdbcServer.java
public static void main(String[] args) { try {/*from w w w . j a v a 2 s .co m*/ File dataDir = new File("target/h2"); String url = "jdbc:h2:tcp://localhost:9092/apiman"; if (dataDir.exists()) { FileUtils.deleteDirectory(dataDir); } dataDir.mkdirs(); Server.createTcpServer("-tcpPassword", "sa", "-baseDir", dataDir.getAbsolutePath(), "-tcpPort", "9092", "-tcpAllowOthers").start(); Class.forName("org.h2.Driver"); try (Connection connection = DriverManager.getConnection(url, "sa", "")) { System.out.println("Connection Established: " + connection.getMetaData().getDatabaseProductName() + "/" + connection.getCatalog()); executeUpdate(connection, "CREATE TABLE users ( username varchar(255) NOT NULL, password varchar(255) NOT NULL, PRIMARY KEY (username))"); executeUpdate(connection, "INSERT INTO users (username, password) VALUES ('bwayne', 'ae2efd698aefdf366736a4eda1bc5241f9fbfec7')"); executeUpdate(connection, "INSERT INTO users (username, password) VALUES ('ckent', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')"); executeUpdate(connection, "INSERT INTO users (username, password) VALUES ('ballen', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')"); executeUpdate(connection, "CREATE TABLE roles (rolename varchar(255) NOT NULL, username varchar(255) NOT NULL)"); executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('user', 'bwayne')"); executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('admin', 'bwayne')"); executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ckent', 'user')"); executeUpdate(connection, "INSERT INTO roles (rolename, username) VALUES ('ballen', 'user')"); } System.out.println("======================================================"); System.out.println("JDBC (H2) server started successfully."); System.out.println(""); System.out.println(" Data: " + dataDir.getAbsolutePath()); System.out.println(" JDBC URL: " + url); System.out.println(" JDBC User: sa"); System.out.println(" JDBC Password: "); System.out.println( " Authentication Query: SELECT * FROM users u WHERE u.username = ? AND u.password = ?"); System.out.println(" Authorization Query: SELECT r.rolename FROM roles r WHERE r.username = ?"); System.out.println("======================================================"); System.out.println(""); System.out.println(""); System.out.println("Press Enter to stop the JDBC server."); new BufferedReader(new InputStreamReader(System.in)).readLine(); System.out.println("Shutting down the JDBC server..."); Server.shutdownTcpServer("tcp://localhost:9092", "", true, true); System.out.println("Done!"); } catch (Exception e) { e.printStackTrace(); } }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.dao.ExtractDataSetForCommonDBUnit.java
public static void main(final String[] args) throws Exception { Connection jdbcConnection = null; FileOutputStream fileOutputStream = null; try {/*w w w .j av a2 s .c o m*/ // database connection Class.forName("org.postgresql.Driver"); jdbcConnection = DriverManager.getConnection(DBURL, DBUser, DBPass); final IDatabaseConnection connection = new DatabaseConnection(jdbcConnection); ITableFilter filter = new DatabaseSequenceFilter(connection); DatabaseConfig config = connection.getConfig(); config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new PostgresqlDataTypeFactory()); QueryDataSet ds = new QueryDataSet(connection, true); ds.addTable("log"); String outputPath = DB_DUMP_FOLDER + DB_DUMP_FILE; //noinspection IOResourceOpenedButNotSafelyClosed fileOutputStream = new FileOutputStream(outputPath); FlatXmlDataSet.write(ds, fileOutputStream); } finally { if (jdbcConnection != null) { jdbcConnection.close(); } IOUtils.closeQuietly(fileOutputStream); } }
From source file:javasnack.cli.CliDbUnitCsvExportDemo.java
public static void main(String[] args) throws Exception { String driver = System.getProperty("CliDbUnitCsvExportDemo.driver", "org.h2.Driver"); Class.forName(driver);//from w w w . j a v a 2 s . co m String url = System.getProperty("CliDbUnitCsvExportDemo.url", "jdbc:h2:mem:CliDbUnitCsvExportDemo"); String dbUser = System.getProperty("CliDbUnitCsvExportDemo.dbUser", "sa"); String dbPassword = System.getProperty("CliDbUnitCsvExportDemo.dbPassword", ""); Connection conn = DriverManager.getConnection(url, dbUser, dbPassword); CliDbUnitCsvExportDemo demo = new CliDbUnitCsvExportDemo(); demo.setup(conn); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); Calendar c = Calendar.getInstance(); File outDir = new File(sdf1.format(c.getTime())); outDir.mkdir(); IDatabaseConnection dbunit_conn = new DatabaseConnection(conn); IDataSet dataSet = dbunit_conn.createDataSet(); CsvBase64BinarySafeDataSetWriter.write(dataSet, outDir); conn.close(); }