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:ChainedExceptionDemo.java

public static void main(String[] args) {
    String driver = "com.mysql.jdbc.Driver";
    String connectionURL = "jdbc:mysql://127.0.0.1:3306/sample";
    try {// w  ww  . j  a  v a2 s.  c  o m
        Class.forName(driver);
    } catch (java.lang.ClassNotFoundException e) {
        e.printStackTrace();
    }
    try {
        conn = DriverManager.getConnection(connectionURL);
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM NONEXISTINGTABLE");
        rs.next();
        rs.close();
    } catch (SQLException sx) {
        for (Throwable e : sx) {
            System.err.println("Error encountered: " + e);
        }
    }
}

From source file:DataInserter.java

public static void main(String args[]) throws Exception {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    DriverManager.registerDriver(new JdbcOdbcDriver());
    String SQLCommand = "INSERT INTO CONTACT_INFO " + "(First_Name,MI,Last_Name,Street,City,State,Zip) "
            + "VALUES " + "('Michael','J','Corleone','86 Horsehead Blvd','NY','NY','12345');";
    String url = "jdbc:odbc:Contacts";
    Connection con = DriverManager.getConnection(url);
    Statement stmt = con.createStatement();
    stmt.execute(SQLCommand);/*from  w ww.j  a va 2 s.  c  om*/
    con.close();

}

From source file:TableMaker.java

public static void main(String[] args) throws Exception {
    Class.forName(jdbcDriver);/*w  w w  .  j av a2  s  .c om*/
    url += dbName;
    Connection con = null;
    Statement stmt = null;
    con = DriverManager.getConnection(url);
    stmt = con.createStatement();
    stmt.execute(SQLCreate);
    con.close();
    if (con != null) {
        con.close();
    }
    if (stmt != null) {
        stmt.close();
    }

}

From source file:CallableStmt.java

public static void main(String args[]) throws Exception {
    String storedProc = "create procedure SHOW_ORDERS_BY_STATE @State CHAR (2) as "
            + "select c.Last_Name+', '+c.First_Name AS Name,o.Order_Number "
            + "from CUSTOMERS c, ORDERS o where c.Customer_Number = o.Customer_Number "
            + "AND c.State = @State order by c.Last_Name;";

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager.getConnection("jdbc:odbc:Customers");
    Statement stmt = con.createStatement();
    stmt.executeUpdate(storedProc);//from  w  w w  .  jav  a2 s .c  o  m
    CallableStatement cs = con.prepareCall("{call SHOW_ORDERS_BY_STATE(?)}");
    cs.setString(1, "NJ");
    ResultSet rs = cs.executeQuery();
    while (rs.next()) {
        String name = rs.getString("Name");
        int orderNo = rs.getInt("Order_Number");
        System.out.println(name + ": " + orderNo);
    }
}

From source file:JavaDBDemo.java

public static void main(String[] args) {
    String driver = "org.apache.derby.jdbc.EmbeddedDriver";
    String connectionURL = "jdbc:derby:myDatabase;create=true";
    String createString = "CREATE TABLE Employee (NAME VARCHAR(32) NOT NULL, ADDRESS VARCHAR(50) NOT NULL)";
    try {//from  w w w . ja  v  a  2s . c  o  m
        Class.forName(driver);
    } catch (java.lang.ClassNotFoundException e) {
        e.printStackTrace();
    }
    try {
        conn = DriverManager.getConnection(connectionURL);
        Statement stmt = conn.createStatement();
        stmt.executeUpdate(createString);

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

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

        psInsert.executeUpdate();

        Statement stmt2 = conn.createStatement();
        ResultSet rs = stmt2.executeQuery("select * from Employee");
        int num = 0;
        while (rs.next()) {
            System.out.println(++num + ": Name: " + rs.getString(1) + "\n Address" + rs.getString(2));
        }
        rs.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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);/*from  ww  w.  jav  a2 s. co  m*/
    }
    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: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   www.  jav a 2  s  .c  om*/

    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:DBCPDemo.java

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

    // create a generic pool
    GenericObjectPool pool = new GenericObjectPool(null);

    // use the connection factory which will wraped by
    // the PoolableConnectionFactory
    DriverManagerConnectionFactory cf = new DriverManagerConnectionFactory(
            "jdbc:jtds:sqlserver://myserver:1433/tandem", "user", "pass");

    PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, pool, null, "SELECT * FROM mysql.db",
            false, true);/*from w w w .  j  a v  a 2  s.c om*/

    // register our pool and give it a name
    new PoolingDriver().registerPool("myPool", pool);

    // get a connection and test it
    Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:myPool");

    // now we can use this pool the way we want.
    System.err.println("Are we connected? " + !conn.isClosed());

    System.err.println("Idle Connections: " + pool.getNumIdle() + ", out of " + pool.getNumActive());

}

From source file:Main.java

public static void main(String args[]) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);//from  w  w  w .  j  av a  2 s.c o m

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager
            .getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/access.mdb");

    ResultSet rs = con.createStatement().executeQuery("select * from product");

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);

    System.out.println(sw.toString());

    con.close();
    rs.close();
}

From source file:movierecommend.MovieRecommend.java

public static void main(String[] args) throws ClassNotFoundException, SQLException {
    String url = "jdbc:sqlserver://localhost;databaseName=MovieDB;integratedSecurity=true";
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection conn = DriverManager.getConnection(url);

    Statement stm = conn.createStatement();
    ResultSet rsRecnik = stm.executeQuery("SELECT Recnik FROM Recnik WHERE (ID_Zanra = 1)"); //citam recnik iz baze za odredjeni zanr
    String recnik[] = null;// ww  w.  j a  v a  2 s . c  o  m

    while (rsRecnik.next()) {
        recnik = rsRecnik.getString("Recnik").split(","); //delim recnik na reci

    }

    ResultSet rsFilmovi = stm.executeQuery(
            "SELECT TOP (200) Naziv_Filma, LemmaPlots, " + "ID_Filma FROM Film WHERE (ID_Zanra = 1)");
    List<Film> listaFilmova = new ArrayList<>();
    Film f = null;
    int rb = 0;
    while (rsFilmovi.next()) {
        f = new Film(rb, Integer.parseInt(rsFilmovi.getString("ID_Filma")), rsFilmovi.getString("Naziv_Filma"),
                rsFilmovi.getString("LemmaPlots"));
        listaFilmova.add(f);
        rb++;

    }
    //kreiranje vektorskog modela
    M = MatrixUtils.createRealMatrix(recnik.length, listaFilmova.size());
    System.out.println("Prva tezinska matrica");

    for (int i = 0; i < recnik.length; i++) {
        String recBaza = recnik[i];
        for (Film film : listaFilmova) {
            for (String lemmaRec : film.getPlotLema()) {
                if (recBaza.equals(lemmaRec)) {
                    M.setEntry(i, film.getRb(), M.getEntry(i, film.getRb()) + 1);
                }
            }
        }
    }
    //racunanje tf-idf
    System.out.println("td-idf");
    M = LSA.calculateTfIdf(M);
    System.out.println("SVD");
    //SVD
    SingularValueDecomposition svd = new SingularValueDecomposition(M);
    RealMatrix V = svd.getV();
    RealMatrix Vk = V.getSubMatrix(0, V.getRowDimension() - 1, 0, brojDimenzija - 1); //dimenzija je poslednji argument
    //kosinusna slicnost
    System.out.println("Cosin simmilarity");
    CallableStatement stmTop = conn.prepareCall("{call Dodaj_TopList(?,?,?)}");

    for (int j = 0; j < listaFilmova.size(); j++) {
        Film fl = listaFilmova.get(j);
        List<Film> lFilmova1 = new ArrayList<>();
        lFilmova1.add(listaFilmova.get(j));
        double sim = 0.0;
        for (int k = 0; k < listaFilmova.size(); k++) {
            // System.out.println(listaFilmova.size());                
            sim = LSA.cosinSim(j, k, Vk.transpose());
            listaFilmova.get(k).setSimilarity(sim);
            lFilmova1.add(listaFilmova.get(k));
        }
        Collections.sort(lFilmova1);
        for (int k = 2; k < 13; k++) {
            stmTop.setString(1, fl.getID() + "");
            stmTop.setString(2, lFilmova1.get(k).getID() + "");
            stmTop.setString(3, lFilmova1.get(k).getSimilarity() + "");
            stmTop.execute();
        }

    }

    stm.close();
    rsRecnik.close();
    rsFilmovi.close();
    conn.close();

}