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) throws SQLException 

Source Link

Document

Attempts to establish a connection to the given database URL.

Usage

From source file:org.ipinfodb.IpInfoDbClient.java

public static void main(String[] args) throws IOException {
    if (args.length < 3 || args.length > 4) {
        System.out.println("Usage: org.ipinfodb.IpInfoDbClient MODE API_KEY [IP_ADDRESS]\n"
                + "MODE can be either 'ip-country' or 'ip-city'.\n"
                + "If you don't have an API_KEY yet, you can get one for free by registering at http://www.ipinfodb.com/register.php.");
        return;// w w  w .java2  s. co  m
    }

    //Code for Reading the multiple ip addresses from a given txt file.
    File inputLogFilePath = new File(args[1]);
    FileReader fr = new FileReader(inputLogFilePath);
    BufferedReader br = new BufferedReader(fr);
    String logLine;
    /*File outputFile=new File("C:/Users/Intelligrape/Desktop/New_Sample_29042014.txt");
    // if file doesnt exists, then create it
       if (!outputFile.exists()) {
          outputFile.createNewFile();
       }
             
    FileWriter fw = new FileWriter(outputFile,true);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write("S.no, IPAddress, Country, Region, City, Zipcode");
    bw.newLine();*/

    try {
        Class.forName("com.mysql.jdbc.Driver");
        System.out.println("Driver found");
    } catch (ClassNotFoundException e) {
        System.out.println("Driver not found: " + e);
    }

    String url_db = "jdbc:mysql://mysqldb.c7zitrf2gguq.us-east-1.rds.amazonaws.com/matse?user=shagun&password=shagun001";

    Connection con = null;

    int insertCounter = 0;
    int count = 1;

    while ((logLine = br.readLine()) != null) {

        String mode = args[2];
        String apiKey = args[3];
        String url = "http://api.ipinfodb.com/v3/" + mode + "/?format=json&key=" + apiKey;
        String[] split = logLine.split(",");
        String ip = split[3];
        url += "&ip=" + ip;

        try {
            HttpGet request = new HttpGet(url);
            HttpResponse response = HTTP_CLIENT.execute(request, new BasicHttpContext());
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new RuntimeException("IpInfoDb response is " + response.getStatusLine());
            }

            String responseBody = EntityUtils.toString(response.getEntity());
            IpCityResponse ipCityResponse = MAPPER.readValue(responseBody, IpCityResponse.class);
            if ("OK".equals(ipCityResponse.getStatusCode())) {
                //System.out.print(count+", "+ip+", "+ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", " + ipCityResponse.getCityName() + ", " + ipCityResponse.zipCode+ ", " + ipCityResponse.countryName + ", " + ipCityResponse.latitude + ", " + ipCityResponse.longitude + ", " + ipCityResponse.timeZone);
                //bw.write(count+", "+ip+", "+ipCityResponse.getCountryCode() + ", " + ipCityResponse.getRegionName() + ", " + ipCityResponse.getCityName() + ", " + ipCityResponse.zipCode + ", " + ipCityResponse.countryName + ", " + ipCityResponse.latitude + ", " + ipCityResponse.longitude + ", " + ipCityResponse.timeZone);

                try {
                    con = DriverManager.getConnection(url_db);
                    //System.out.println("Connected successfully"); 
                    Statement stmt = con.createStatement();
                    //System.out.println(logLine);
                    //System.out.println(split.length);
                    int result = stmt.executeUpdate("INSERT INTO LOGDATA1 VALUES('" + split[0] + "','"
                            + split[1].trim() + "','" + split[2] + "','" + split[3] + "','" + split[4] + "','"
                            + ipCityResponse.statusCode + "','" + ipCityResponse.countryCode + "','"
                            + ipCityResponse.countryName + "','" + ipCityResponse.regionName + "','"
                            + ipCityResponse.cityName + "','" + ipCityResponse.zipCode + "','"
                            + ipCityResponse.latitude + "','" + ipCityResponse.longitude + "','"
                            + ipCityResponse.timeZone + "')");
                    ++insertCounter;
                    con.close();
                    System.out.println(insertCounter);
                } catch (SQLException e) {
                    System.out.println("something wrong in the connection string: " + e);
                }

            } else {
                System.out.print("API status message is '" + ipCityResponse.getStatusMessage() + "'");
            }
        } finally {

            //HTTP_CLIENT.getConnectionManager().shutdown();

        }
        ++count;

    }
    HTTP_CLIENT.getConnectionManager().shutdown();

}

From source file:au.edu.flinders.ehl.filmweekly.FwImporter.java

/**
 * Main method for the class//w w  w  .  j  a v  a 2  s . c  o m
 * 
 * @param args array of command line arguments
 */
public static void main(String[] args) {

    // before we do anything, output some useful information
    for (int i = 0; i < APP_HEADER.length; i++) {
        System.out.println(APP_HEADER[i]);
    }

    // parse the command line options
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(createOptions(), args);
    } catch (org.apache.commons.cli.ParseException e) {
        // something bad happened so output help message
        printCliHelp("Error in parsing options:\n" + e.getMessage());
    }

    // get and check on the log4j properties path option if required
    if (cmd.hasOption("log4j") == true) {
        String log4jPath = cmd.getOptionValue("log4j");
        if (FileUtils.isAccessible(log4jPath) == false) {
            printCliHelp("Unable to access the specified log4j properties file\n   " + log4jPath);
        }

        // configure the log4j framework
        PropertyConfigurator.configure(log4jPath);
    }

    // get and check on the properties path option
    String propertiesPath = cmd.getOptionValue("properties");
    if (FileUtils.isAccessible(propertiesPath) == false) {
        printCliHelp("Unable to access the specified properties file\n   " + propertiesPath);
    }

    // get and check on the input file path option
    String inputPath = cmd.getOptionValue("input");
    if (FileUtils.isAccessible(inputPath) == false) {
        printCliHelp("Unable to access the specified input file");
    }

    // open the properties file
    Configuration config = null;
    try {
        config = new PropertiesConfiguration(propertiesPath);
    } catch (ConfigurationException e) {
        printCliHelp("Unable to read the properties file file: \n" + e.getMessage());
    }

    // check to make sure all of the required configuration properties are present
    for (int i = 0; i < REQD_PROPERTIES.length; i++) {
        if (config.containsKey(REQD_PROPERTIES[i]) == false) {
            printCliHelp("Unable to find the required property: " + REQD_PROPERTIES[i]);
        }
    }

    if (cmd.hasOption("debug_coord_list") == true) {

        // output debug info
        logger.debug("undertaking the debug-coord-list task");

        // undertake the debug coordinate list task
        if (FileUtils.doesFileExist(cmd.getOptionValue("debug_coord_list")) == true) {
            printCliHelp("the debug_coord_list file already exists");
        } else {
            CoordList list = new CoordList(inputPath, cmd.getOptionValue("debug_coord_list"));

            try {
                list.openFiles();
                list.doTask();
            } catch (IOException e) {
                logger.error("unable to undertake the debug-coord-list task", e);
                errorExit();
            }

            System.out.println("Task completed");
            System.exit(0);
        }
    }

    if (cmd.hasOption("debug_json_list") == true) {

        // output debug info
        logger.debug("undertaking the debug-json-list task");

        // undertake the debug coordinate list task
        if (FileUtils.doesFileExist(cmd.getOptionValue("debug_json_list")) == true) {
            printCliHelp("the debug_json_list file already exists");
        } else {
            JsonList list = new JsonList(inputPath, cmd.getOptionValue("debug_json_list"));

            try {
                list.openFiles();
                list.doTask();
            } catch (IOException e) {
                logger.error("unable to undertake the debug_json_list task", e);
                errorExit();
            }

            System.out.println("Task completed");
            System.exit(0);
        }
    }

    // if no debug options present assume import
    System.out.println("Importing data into the database.");
    System.out.println(
            "*Note* if this input file has been processed before duplicate records *will* be created.");

    // get a connection to the database
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception e) {
        logger.error("unable to load the MySQL database classes", e);
        errorExit();
    }

    Connection database = null;

    //private static final String[] REQD_PROPERTIES = {"db-host", "db-user", "db-password", "db-name"};

    String connectionString = "jdbc:mysql://" + config.getString(REQD_PROPERTIES[0]) + "/"
            + config.getString(REQD_PROPERTIES[1]) + "?user=" + config.getString(REQD_PROPERTIES[2])
            + "&password=" + config.getString(REQD_PROPERTIES[3]);

    try {
        database = DriverManager.getConnection(connectionString);
    } catch (SQLException e) {
        logger.error("unable to connect to the MySQL database", e);
        errorExit();
    }

    // do the import
    DataImporter importer = new DataImporter(database, inputPath);

    try {
        importer.openFiles();
        importer.doTask();

        System.out.println("Task completed");
        System.exit(0);
    } catch (IOException e) {
        logger.error("unable to complete the import");
        errorExit();
    } catch (ImportException e) {
        logger.error("unable to complete the import");
        errorExit();
    } finally {
        // play nice and tidy up
        try {
            database.close();
        } catch (SQLException e) {
            logger.error("Unable to close the database connection: ", e);
        }

    }
}

From source file:MainClass.java

public static void createDatabase() {
    String data = "jdbc:derby:presidents;create=true";
    try {/*w  w  w .  j a  v  a  2 s  . c o  m*/
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
        Connection conn = DriverManager.getConnection(data);
        Statement st = conn.createStatement();
        int result = st.executeUpdate("CREATE TABLE contacts (dex INTEGER NOT NULL PRIMARY KEY "
                + "GENERATED ALWAYS AS identity (START WITH 1, INCREMENT BY 1), "
                + "name VARCHAR(40), address1 VARCHAR(40), address2 VARCHAR(40))");

        result = st.executeUpdate(
                "INSERT INTO contacts (name, address1, address2" + ") VALUES('J','Center', 1 , 'GA')");
        st.close();
    } catch (Exception e) {
        System.out.println("Error - " + e.toString());
    }
}

From source file:com.mirth.connect.server.tools.ScriptRunner.java

public static void runScript(String scriptFile) {
    try {/*from  ww  w  . ja  v a2  s.  c om*/
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
        Connection connection = DriverManager.getConnection("jdbc:derby:mirthdb;create=true");
        InputStream in = new FileInputStream(new File(scriptFile));
        OutputStream out = new NullOutputStream();
        ij.runScript(connection, in, "UTF-8", out, "UTF-8");
    } catch (Exception e) {
        logger.error("error executing script", e);
    }
}

From source file:org.works.integration.storedproc.derby.DerbyStoredProcedures.java

public static void findCoffee(int coffeeId, String[] coffeeDescription) throws SQLException {
    Connection connection = null;
    PreparedStatement statement = null;

    try {//from   ww w  .ja  va2  s  .  co m
        connection = DriverManager.getConnection("jdbc:default:connection");
        String sql = "SELECT * FROM COFFEE_BEVERAGES WHERE ID = ? ";
        statement = connection.prepareStatement(sql);
        statement.setLong(1, coffeeId);

        ResultSet resultset = statement.executeQuery();
        resultset.next();
        coffeeDescription[0] = resultset.getString("COFFEE_DESCRIPTION");

    } finally {
        JdbcUtils.closeStatement(statement);
        JdbcUtils.closeConnection(connection);
    }

}

From source file:MainClass.java

public MainClass() {
    try {//from  w w  w.j  ava2s. c o m
        Class.forName("COM.cloudscape.core.RmiJdbcDriver");
        Connection connection = DriverManager.getConnection("jdbc:cloudscape:rmi:books");
        Statement statement = connection.createStatement();
        ResultSet resultSet = statement.executeQuery("SELECT * FROM authors");
        ResultSetMetaData metaData = resultSet.getMetaData();
        int numberOfColumns = metaData.getColumnCount();

        for (int i = 1; i <= numberOfColumns; i++) {
            System.out.println(metaData.getColumnName(i) + "\t");
        }

        while (resultSet.next()) {

            for (int i = 1; i <= numberOfColumns; i++) {
                System.out.println(resultSet.getObject(i) + "\t");
            }

            System.out.println("\n");
        }

        statement.close();
        connection.close();
    } catch (SQLException sqlException) {
        System.out.println(sqlException.getMessage());
    } catch (ClassNotFoundException classNotFound) {
        System.out.println("Driver Not Found");
        System.exit(1);
    }
}

From source file:EnumTesting.java

public EnumTesting() {
    try {// w ww .  ja  v a 2 s. c o  m
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = DriverManager.getConnection("jdbc:mysql://192.168.1.25/test?user=spider&password=spider");
    } catch (Exception e) {
        System.err.println("Unable to find and load driver");
        System.exit(1);
    }
}

From source file:Transaction.java

public Transaction() {
    try {/*from w w w.  j av  a 2 s  .co m*/
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = DriverManager
                .getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider");
    } catch (Exception e) {
        System.err.println("Unable to find and load driver");
        System.exit(1);
    }
}

From source file:Thumbnail.java

public Thumbnail() {
    try {//ww  w.j a v  a 2 s  .  c  o  m
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = DriverManager
                .getConnection("jdbc:mysql://192.168.1.25/identification?user=spider&password=spider");
    } catch (Exception e) {
        System.err.println("Unable to find and load driver");
        System.exit(1);
    }
}

From source file:de.dakror.virtualhub.server.DBManager.java

public static void init() {
    try {/*from  w w w.  j  a va  2  s  . c  o m*/
        database = new File(Server.dir, "virtualhub.db");
        database.createNewFile();

        Class.forName("org.sqlite.JDBC");
        connection = DriverManager.getConnection("jdbc:sqlite:" + database.getPath().replace("\\", "/"));

        Statement s = connection.createStatement();
        s.executeUpdate(
                "CREATE TABLE IF NOT EXISTS ETICETS(PATH varchar(500) NOT NULL PRIMARY KEY, CATALOG varchar(100), ETICET INT)");
        s.executeUpdate(
                "CREATE TABLE IF NOT EXISTS TAGS(PATH varchar(500) NOT NULL PRIMARY KEY, CATALOG varchar(100), TAGS TEXT)");
    } catch (Exception e) {
        e.printStackTrace();
    }
}