Example usage for java.lang Class forName

List of usage examples for java.lang Class forName

Introduction

In this page you can find the example usage for java.lang Class forName.

Prototype

@CallerSensitive
public static Class<?> forName(String className) throws ClassNotFoundException 

Source Link

Document

Returns the Class object associated with the class or interface with the given string name.

Usage

From source file:Main.java

public static void main(String[] args) {
    Connection conn = null;/*from   w  w  w  .  j a v a 2  s .com*/
    Statement stmt = null;
    try {
        // Register JDBC driver
        Class.forName(JDBC_DRIVER);

        // Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        // Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT id, first, last, age FROM Employees";
        stmt.executeUpdate(
                "CREATE TABLE Employees ( id INTEGER IDENTITY, first VARCHAR(256),  last VARCHAR(256),age INTEGER)");
        stmt.executeUpdate("INSERT INTO Employees VALUES(1,'Jack','Smith', 100)");

        ResultSet rs = stmt.executeQuery(sql);

        // Extract data from result set
        while (rs.next()) {
            // Retrieve by column name
            int id = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            System.out.print("ID: " + id);
            System.out.print(", Age: " + age);
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
        }
        // Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
    System.out.println("Goodbye!");
}

From source file:Main.java

public static void main(String[] args) {
    Connection conn = null;//from w  ww . j a v a  2 s .c  o  m
    Statement stmt = 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);

        // STEP 4: Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT id, first, last, age FROM Employees";
        stmt.executeUpdate(
                "CREATE TABLE Employees ( id INTEGER IDENTITY, first VARCHAR(256),  last VARCHAR(256),age INTEGER)");
        stmt.executeUpdate("INSERT INTO Employees VALUES(1,'Jack','Smith', 100)");

        ResultSet rs = stmt.executeQuery(sql);

        // STEP 5: Extract data from result set
        while (rs.next()) {
            // Retrieve by column name
            int id = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            System.out.print("ID: " + id);
            System.out.print(", Age: " + age);
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
        }
        // STEP 6: Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
    System.out.println("Goodbye!");
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    KeyGenerator kg = KeyGenerator.getInstance("DES");
    kg.init(new SecureRandom());
    SecretKey key = kg.generateKey();
    SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
    Class spec = Class.forName("javax.crypto.spec.DESKeySpec");
    DESKeySpec ks = (DESKeySpec) skf.getKeySpec(key, spec);
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keyfile"));
    oos.writeObject(ks.getKey());/*from www . j av  a  2 s  .co m*/

    Cipher c = Cipher.getInstance("DES/CFB8/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, key);
    CipherOutputStream cos = new CipherOutputStream(new FileOutputStream("ciphertext"), c);
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(cos));
    pw.println("Stand and unfold yourself");
    pw.close();
    oos.writeObject(c.getIV());
    oos.close();
}

From source file:Logging.java

public static void main(String args[]) throws Exception {
    FileOutputStream errors = new FileOutputStream("StdErr.txt", true);
    PrintStream stderr = new PrintStream(errors);
    PrintWriter errLog = new PrintWriter(errors, true);
    System.setErr(stderr);/*from  ww  w. j  a  va2s.co  m*/

    String query = "SELECT Name,Description,Qty,Cost,Sell_Price FROM Stock";

    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con = DriverManager.getConnection("jdbc:odbc:Inventory");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);
        while (rs.next()) {
            String name = rs.getString("Name");
            String desc = rs.getString("Description");
            int qty = rs.getInt("Qty");
            float cost = rs.getFloat("Cost");
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace(errLog);
    } catch (SQLException e) {
        System.err.println((new GregorianCalendar()).getTime());
        System.err.println("Thread: " + Thread.currentThread());
        System.err.println("ErrorCode: " + e.getErrorCode());
        System.err.println("SQLState:  " + e.getSQLState());
        System.err.println("Message:   " + e.getMessage());
        System.err.println("NextException: " + e.getNextException());
        e.printStackTrace(errLog);
        System.err.println();
    }
    stderr.close();
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println("Usage: java JavaDBDemo <Name> <Address>");
        System.exit(1);// w w  w  . j  a  v a  2  s  .  c  om
    }
    String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    String dbName = "AddressBookDB";
    String connectionURL = "jdbc:derby:" + dbName + ";create=true";
    String createString = "CREATE TABLE ADDRESSBOOKTbl (NAME VARCHAR(32) NOT NULL, ADDRESS VARCHAR(50) NOT NULL)";
    Class.forName(driver);

    conn = DriverManager.getConnection(connectionURL);

    Statement stmt = conn.createStatement();
    stmt.executeUpdate(createString);

    PreparedStatement psInsert = conn.prepareStatement("insert into ADDRESSBOOKTbl values (?,?)");

    psInsert.setString(1, args[0]);
    psInsert.setString(2, args[1]);

    psInsert.executeUpdate();

    Statement stmt2 = conn.createStatement();
    ResultSet rs = stmt2.executeQuery("select * from ADDRESSBOOKTbl");
    System.out.println("Addressed present in your Address Book\n\n");
    int num = 0;

    while (rs.next()) {
        System.out.println(++num + ": Name: " + rs.getString(1) + "\n Address" + rs.getString(2));
    }
    rs.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = null;// w  w  w.  j  a  va 2 s  .c om
    PreparedStatement pstmt = null;
    Statement stmt = null;
    ResultSet rs = null;
    Class.forName(JDBC_DRIVER);
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    stmt = conn.createStatement();
    createXMLTable(stmt);
    File f = new File("build.xml");
    long fileLength = f.length();
    FileInputStream fis = new FileInputStream(f);
    String SQL = "INSERT INTO XML_Data VALUES (?,?)";
    pstmt = conn.prepareStatement(SQL);
    pstmt.setInt(1, 100);
    pstmt.setAsciiStream(2, fis, (int) fileLength);
    pstmt.execute();
    fis.close();
    SQL = "SELECT Data FROM XML_Data WHERE id=100";
    rs = stmt.executeQuery(SQL);
    if (rs.next()) {
        InputStream xmlInputStream = rs.getAsciiStream(1);
        int c;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((c = xmlInputStream.read()) != -1)
            bos.write(c);
        System.out.println(bos.toString());
    }
    rs.close();
    stmt.close();
    pstmt.close();
    conn.close();
}

From source file:ReverseSelect.java

public static void main(String argv[]) {
    Connection con = null;// w w w.ja  v a  2  s  .  co  m

    try {
        String url = "jdbc:msql://carthage.imaginary.com/ora";
        String driver = "com.imaginary.sql.msql.MsqlDriver";
        Properties p = new Properties();
        Statement stmt;
        ResultSet rs;

        p.put("user", "borg");
        Class.forName(driver).newInstance();
        con = DriverManager.getConnection(url, "borg", "");
        stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = stmt.executeQuery("SELECT * from test ORDER BY test_id");
        // as a new ResultSet, rs is currently positioned
        // before the first row
        System.out.println("Got results:");
        // position rs after the last row
        rs.afterLast();
        while (rs.previous()) {
            int a = rs.getInt("test_id");
            String str = rs.getString("test_val");

            System.out.print("\ttest_id= " + a);
            System.out.println("/str= '" + str + "'");
        }
        System.out.println("Done.");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

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;//  w  w w .j av a 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:com.jeffy.hdfs.compression.StreamCompressor.java

public static void main(String[] args) throws ClassNotFoundException, IOException {
    //// w  ww. j  a  v a 2s  . c  om
    String codecClassname = args[0];

    Class<?> codecClass = Class.forName(codecClassname);

    Configuration conf = new Configuration();

    CompressionCodec codec = (CompressionCodec) ReflectionUtils.newInstance(codecClass, conf);

    CompressionOutputStream out = codec.createOutputStream(System.out);

    IOUtils.copy(System.in, out);

    out.finish();

}

From source file:Main.java

public static void main(String[] args) throws ClassNotFoundException, SQLException {
    Class.forName(DRIVER);
    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));
        }// w  w w  .  j a v  a 2 s .com
    }
}