Example usage for java.sql DriverManager getConnection

List of usage examples for java.sql DriverManager getConnection

Introduction

In this page you can find the example usage for java.sql DriverManager getConnection.

Prototype

@CallerSensitive
public static Connection getConnection(String url, java.util.Properties info) throws SQLException 

Source Link

Document

Attempts to establish a connection to the given database URL.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

    Properties prop = new Properties();
    prop.put("charSet", "iso-8859-7");
    prop.put("user", "your username");
    prop.put("password", "your password");

    // Connect to the database
    Connection con = DriverManager.getConnection("url", prop);

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = null;/*ww  w .  j  a v  a2  s  . c om*/
    Properties info = new Properties();
    // info.put("proxy_type", "4"); // SSL Tunneling
    info.put("proxy_host", "[proxy host]");
    info.put("proxy_port", "[proxy port]");
    info.put("proxy_user", "[proxy user]");
    info.put("proxy_password", "[proxy password]");
    info.put("user", "[db user]");
    info.put("password", "[db pass word]");
    conn = DriverManager.getConnection("jdbc:mysql://[db host]/", info);

    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("Select NOW()");
    rs.next();
    System.out.println("Data- " + rs.getString(1));
    rs.close();
    stmt.close();
    conn.close();
}

From source file:TestDataEncryptionIntegrity.java

public static void main(String[] argv) throws Exception {

    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

    Properties prop = new Properties();
    prop.setProperty("user", "scott");
    prop.setProperty("password", "tiger");
    prop.setProperty("oracle.net.encryption_client", "REQUIRED");
    prop.setProperty("oracle.net.encryption_types_client", "( RC4_40 )");
    prop.setProperty("oracle.net.crypto_checksum_client", "REQUIRED");
    prop.setProperty("oracle.net.crypto_checksum_types_client", "( MD5 )");

    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@dssw2k01:1521:orcl", prop);
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt.executeQuery(
            "select 'Hello Thin driver Encryption & Integrity " + "tester '||USER||'!' result from dual");
    while (rset.next())
        System.out.println(rset.getString(1));
    rset.close();/*from   w w w.jav a 2  s  .com*/
    stmt.close();
    conn.close();
}

From source file:TestSSL.java

public static void main(String[] argv) throws Exception {

    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

    Properties prop = new Properties();
    prop.setProperty("user", "scott");
    prop.setProperty("password", "tiger");
    // THIS DOES NOT WORK YET
    prop.setProperty("oracle.net.ssl_cipher_suites",
            "(ssl_rsa_export_with_rc4_40_md5, ssl_rsa_export_with_des40_cbc_sha)");
    prop.setProperty("oracle.net.ssl_client_authentication", "false");
    prop.setProperty("oracle.net.ssl_version", "3.0");
    prop.setProperty("oracle.net.encryption_client", "REJECTED");
    prop.setProperty("oracle.net.crypto_checksum_client", "REJECTED");
    Connection conn = DriverManager.getConnection(
            "jdbc:oracle:thin:@(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCPS)(HOST = dssw2k01)(PORT = 2484))) (CONNECT_DATA = (SERVICE_NAME = DSSW2K01)))",
            prop);//  ww  w.jav  a2 s  .c o m
    Statement stmt = conn.createStatement();
    ResultSet rset = stmt
            .executeQuery("select 'Hello Thin driver SSL " + "tester '||USER||'!' result from dual");
    while (rset.next())
        System.out.println(rset.getString(1));
    rset.close();
    stmt.close();
    conn.close();
}

From source file:TerminalMonitor.java

static public void main(String args[]) {
    DriverPropertyInfo[] required;
    StringBuffer buffer = new StringBuffer();
    Properties props = new Properties();
    boolean connected = false;
    Driver driver;//w w w.  j av a 2  s . c  om
    String url;
    int line = 1; // Mark current input line

    if (args.length < 1) {
        System.out.println("Syntax: <java -Djdbc.drivers=DRIVER_NAME " + "TerminalMonitor JDBC_URL>");
        return;
    }
    url = args[0];
    // We have to get a reference to the driver so we can
    // find out what values to prompt the user for in order
    // to make a connection.
    try {
        driver = DriverManager.getDriver(url);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to find a driver for the specified " + "URL.");
        System.err.println("Make sure you passed the jdbc.drivers " + "property on the command line to specify "
                + "the driver to be used.");
        return;
    }
    try {
        required = driver.getPropertyInfo(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to get driver property information.");
        return;
    }
    input = new BufferedReader(new InputStreamReader(System.in));
    // some drivers do not implement this properly
    // if that is the case, prompt for user name and password
    try {
        if (required.length < 1) {
            props.put("user", prompt("user: "));
            props.put("password", prompt("password: "));
        } else {
            // for each required attribute in the driver property info
            // prompt the user for the value
            for (int i = 0; i < required.length; i++) {
                if (!required[i].required) {
                    continue;
                }
                props.put(required[i].name, prompt(required[i].name + ": "));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("Unable to read property info.");
        return;
    }
    // Make the connection.
    try {
        connection = DriverManager.getConnection(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to connect to the database.");
    }
    connected = true;
    System.out.println("Connected to " + url);
    // Enter into a user input loop
    while (connected) {
        String tmp, cmd;

        // Print a prompt
        if (line == 1) {
            System.out.print("TM > ");
        } else {
            System.out.print(line + " -> ");
        }
        System.out.flush();
        // Get the next line of input
        try {
            tmp = input.readLine();
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return;
        }
        // Get rid of extra space in the command
        cmd = tmp.trim();
        // The user wants to commit pending transactions
        if (cmd.equals("commit")) {
            try {
                connection.commit();
                System.out.println("Commit successful.");
            } catch (SQLException e) {
                System.out.println("Error in commit: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants to execute the current buffer
        else if (cmd.equals("go")) {
            if (!buffer.equals("")) {
                try {
                    executeStatement(buffer);
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to quit
        else if (cmd.equals("quit")) {
            connected = false;
            continue;
        }
        // The user wants to clear the current buffer
        else if (cmd.equals("reset")) {
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to abort a pending transaction
        else if (cmd.equals("rollback")) {
            try {
                connection.rollback();
                System.out.println("Rollback successful.");
            } catch (SQLException e) {
                System.out.println("An error occurred during rollback: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants version info
        else if (cmd.startsWith("show")) {
            DatabaseMetaData meta;

            try {
                meta = connection.getMetaData();
                cmd = cmd.substring(5, cmd.length()).trim();
                if (cmd.equals("version")) {
                    showVersion(meta);
                } else {
                    System.out.println("show version"); // Bad arg
                }
            } catch (SQLException e) {
                System.out.println("Failed to load meta data: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The input that is not a keyword should appended be to the buffer
        else {
            buffer.append(" " + tmp);
            line++;
            continue;
        }
    }
    try {
        connection.close();
    } catch (SQLException e) {
        System.out.println("Error closing connection: " + e.getMessage());
    }
    System.out.println("Connection closed.");
}

From source file:ca.uwaterloo.iss4e.algorithm.PARX.java

public static void main(String[] args) {

    String url = "jdbc:postgresql://localhost/essex";
    Properties props = new Properties();
    props.setProperty("user", "xiliu");
    props.setProperty("password", "Abcd1234");

    try {//from ww  w .j  a va  2 s.c  o m
        /* Random generator = new Random();
         BigDecimal[] d = new BigDecimal[40];
         for (int i=0; i<40; ++i){
        d[i] = new BigDecimal(generator.nextInt(10));
        System.out.print(d[i].doubleValue()+"("+i+") |");
         }
         System.out.println("\n ---------------");
         Pair<double[], double[][]> values = PARX.prepareVariable(d, 11, 12, 2, 4);
         double[] Y = values.getKey();
         double X[][] = values.getValue();
         for (int i=0; i<Y.length; ++i){
                
        for (int j=0; j<X[i].length; ++j) {
            System.out.print(X[i][j] + " |");
        }
        System.out.print("|" +Y[i]);
        System.out.println();
         }
        */

        Class.forName("org.postgresql.Driver");
        Connection conn = DriverManager.getConnection(url, props);
        PreparedStatement pstmt = conn.prepareStatement(
                "select array_agg(A.reading) from (select reading from meterreading where homeid=? and readdate between ? and ? order by readdate desc, readtime desc) A ");
        pstmt.setInt(1, 19419);
        pstmt.setDate(2, java.sql.Date.valueOf("2011-04-03"));
        pstmt.setDate(3, java.sql.Date.valueOf("2011-09-07"));

        ResultSet rs = pstmt.executeQuery();

        int order = 3;

        int numOfSeasons = 24;
        int intervalOfUpdateModel = 4; //Every four hours
        int startPredict = 6 * 24;
        int numOfPointsForTraining = 24 * 5;
        double[] pointsForPredict = new double[order];

        if (rs.next()) {
            BigDecimal[] readings = (BigDecimal[]) (rs.getArray(1).getArray());
            double[][] data = new double[2][readings.length + 1];
            int i = 0;
            for (; i < startPredict; ++i) {
                data[0][i] = readings[i].doubleValue();
                data[1][i] = 0.0;
            }

            double[] beta = null;
            int updateModelCount = 0;
            for (; i < readings.length; ++i) {
                // if (updateModelCount%intervalOfUpdateModel==0) {
                // beta = PARX.computePARModel(readings, i, i+1, order, numOfSeasons);
                ++updateModelCount;
                //}
                for (int p = 0; p < order; ++p) {
                    pointsForPredict[order - 1 - p] = readings[i - p].doubleValue();
                }
                data[0][i] = readings[i].doubleValue();
                //   data[1][i+1] = PARX.predict(pointsForPredict, order, beta);
            }

            for (int j = 0; j < readings.length + 1; ++j) {
                System.out.println(data[0][j] + ", " + data[1][j]);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static Connection getConnection(String dbURL, String user, String password)
        throws SQLException, ClassNotFoundException {
    Class.forName("com.mysql.jdbc.Driver");

    Properties props = new Properties();
    props.put("user", user);
    props.put("password", password);

    props.put("autoReconnect", "true");

    return DriverManager.getConnection(dbURL, props);
}

From source file:TestCreateConnectionWithProperties_MySQL.java

public static Connection getConnection() throws Exception {
    String driver = "org.gjt.mm.mysql.Driver";
    // load the driver
    Class.forName(driver);//from   w w  w .j a  v  a 2  s .c  o m
    String dbURL = "jdbc:mysql://localhost/databaseName";
    String dbUsername = "root";
    String dbPassword = "root";

    java.util.Properties connProperties = new java.util.Properties();
    connProperties.put(DATABASE_USER, dbUsername);
    connProperties.put(DATABASE_PASSWORD, dbPassword);

    // set additional connection properties:
    // if connection stales, then make automatically
    // reconnect; make it alive again;
    // if connection stales, then try for reconnection;
    connProperties.put(MYSQL_AUTO_RECONNECT, "true");
    connProperties.put(MYSQL_MAX_RECONNECTS, "4");
    Connection conn = DriverManager.getConnection(dbURL, connProperties);
    return conn;
}

From source file:Main.java

public static Connection connectToDatabase(String propertiesFileName) throws Exception {
    Properties dbProps = new Properties();
    Properties dumpProps = new Properties();
    dbProps.load(new FileInputStream(propertiesFileName));
    dumpProps.load(new FileInputStream(propertiesFileName));
    System.out.println("Database Properties");
    dumpProps.remove("password");
    dumpProps.list(System.out);/*w w w  . jav a2s .c  o m*/
    System.out.println("Loading Driver");
    Class.forName(dbProps.getProperty("dbDriver"));

    System.out.println("Connecting to Database...");
    Connection con = DriverManager.getConnection(dbProps.getProperty("dbURL"), dbProps);
    System.out.println("Connected");
    return con;
}

From source file:Main.java

/**
 * Helper method to create a Redshift table
 * /*from  w  ww  .  j  a v  a 2s.  c  o m*/
 * @param redshiftURL
 *            The JDBC URL of the Redshift database
 * @param loginProperties
 *            A properties file containing the authentication credentials for the database
 * @param tableName
 *            The table to create
 * @param fields
 *            A list of column specifications that will be comma separated in the create table
 *            statement
 * @throws SQLException
 *             Table creation failed
 */
public static void createRedshiftTable(String redshiftURL, Properties loginProperties, String tableName,
        List<String> fields) throws SQLException {
    Connection conn = DriverManager.getConnection(redshiftURL, loginProperties);
    Statement stmt = conn.createStatement();
    stmt.execute("CREATE TABLE " + tableName + " " + toSQLFields(fields) + ";");
    stmt.close();
    conn.close();
}