Пример #1
0
  public static void main(String[] args)
      throws SQLException, ClassNotFoundException, JSONException {
    PostgresDb db = new PostgresDb();
    // db.setUrl("jdbc:postgresql://localhost:5432/powaaim");

    try {
      Class.forName("org.postgresql.Driver");
      c = DriverManager.getConnection(db.getUrl(), db.getUser(), db.getPass());
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    st = c.createStatement();
    rs = st.executeQuery("SELECT id, name, externalshopid from shop where name='David_3'");
    System.out.println("id" + " " + "name" + " " + "externalshopid");
    c.close();
    obj = new JSONObject();

    while (rs.next()) {
      int id = rs.getInt("id");
      String externaId = rs.getString("externalshopid");
      String name = rs.getString("name");
      // System.out.println(id+ " " + " "+ name + " " +" "+ externaId);
      System.out.println();
      obj.put("id", id);
      obj.put("name", name);
      obj.put("externalshopid", externaId);
      System.out.print(obj);
    }
  }
 public Connection createConnection() throws Exception {
   Connection con;
   try {
     Class.forName(dbClass);
     con = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
   } catch (Exception e) {
     e.printStackTrace();
     throw e;
   }
   return con;
 }
Пример #3
0
  /**
   * Establece una conexión con la base de datos, usando el usuario y clave especificados. Si ya hay
   * una conexi�n, esta es cerrada.
   *
   * @param usuario Una cadena con el nombre de usuario
   * @param clave Una cadena con la clave
   * @return Regresa verdadero (true) si pudo establecer la conexión de lo contrario regresa falso
   *     (false).
   */
  protected boolean conectar(String usuario, String clave) throws Exception {

    // Registra el controlador de manera implicita
    Class.forName(controlador).newInstance();
    // Obtiene la conexión
    System.err.println(url + "," + usuario + "," + clave + ":OK!!!");
    this.conexión = DriverManager.getConnection(url, usuario, clave);
    // Actualiza usuario y clave del middler
    this.usuario = usuario;
    this.clave = clave;
    return this.conexión != null;
  } // Fin conectar
Пример #4
0
 public static Connection getConnect() {
   try {
     /*if (!getConnect) {
     if (!con.isValid(1)) {*/
     String host = "jdbc:mysql://localhost:3306/2761DB";
     String uname = "root";
     String upassword = "******";
     con = DriverManager.getConnection(host, uname, upassword);
     getConnect = true;
     /*}
     }*/
   } catch (SQLException err) {
     System.out.println(err.getMessage());
   }
   return con;
 }
Пример #5
0
 public CachedRowSet query(String sql, int pageSize, int page) throws Exception {
   // 加载驱动
   Class.forName(driver);
   try (
   // 获取数据库连接
   Connection conn = DriverManager.getConnection(url, user, pass);
       Statement stmt = conn.createStatement();
       ResultSet rs = stmt.executeQuery(sql)) {
     // 使用RowSetProvider创建RowSetFactory
     RowSetFactory factory = RowSetProvider.newFactory();
     // 创建默认的CachedRowSet实例
     CachedRowSet cachedRs = factory.createCachedRowSet();
     // 设置每页显示pageSize条记录
     cachedRs.setPageSize(pageSize);
     // 使用ResultSet装填RowSet,设置从第几条记录开始
     cachedRs.populate(rs, (page - 1) * pageSize + 1);
     return cachedRs;
   }
 }
Пример #6
0
  public static void main(String[] args) {
    Connection con = null;
    Statement stat = null;
    String s;
    try {
      Class.forName("oracle.jdbc.driver.OracleDriver");

      //    con=DriverManager.getConnection("jdbc:oracle:oci8:@oracle9i","scott","tiger");

      //
      // con=DriverManager.getConnection("jdbc:oracle:thin:@saraswati:1521:oracle10g","scott","tiger");
      con = DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/XE", "scott", "tiger");

      /*Properties p=new Properties();
      p.put("user","scott");
      p.put("password","tiger");*/

      // Driver d=(Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

      // Connection con=d.connect("jdbc:odbc:oradsn",p);

      // Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      // con=DriverManager.getConnection("jdbc:odbc:namadsn","scott","tiger");

      System.out.println("The connection is successful.");
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      stat = con.createStatement();
      s = "create table student(Rollno int,Name varchar2(50),serName varchar2(50))";
      stat.executeUpdate(s);
    } catch (SQLException e) {
      e.printStackTrace();
    }

    try {
      stat = con.createStatement();
      s = "insert into student values(1,'Namrata','Marathe')";
      stat.executeUpdate(s);
      s = "insert into student values(2,'Arjun','Marathe')";
      stat.executeUpdate(s);
      s = "insert into student values(3,'Rahul','Marathe')";
      stat.executeUpdate(s);

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

    try {
      stat.close();
    } catch (SQLException e) {
    }

    System.out.println("create is successful:");

    try {
      stat = con.createStatement();
      s = "select * from student";
      ResultSet rset = stat.executeQuery(s);

      while (rset.next())
        System.out.println(rset.getInt(1) + " " + rset.getString(2) + "    " + rset.getString(3));
    } catch (SQLException e) {
      e.printStackTrace();
    }

    try {
      stat.close();
    } catch (SQLException se) {

    }
  }
Пример #7
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    server svr = new server();
    response.setContentType("text/html");
    HttpSession session = request.getSession(true);
    PrintWriter out = response.getWriter();
    String email = request.getParameter("email");
    String pw1 = request.getParameter("pw1");
    String pw2 = request.getParameter("pw2");
    String error = null;
    String username = session.getAttribute("username").toString();
    if (pw1.compareTo(pw2) != 0) {
      error = "Passwords do not match";
      session.setAttribute("ErrorMessage", error);
      response.sendRedirect("home.jsp");
    }
    try {
      Statement st = null;
      String strQuery = null;
      if ((pw1.length() == 0) && (email.length() == 0)) {
        session.setAttribute("ErrorMessage", "Nothing to change!");
        response.sendRedirect("home.jsp");
      } else if ((pw1.length() != 0) && (email.length() != 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `password`='"
                + pw1
                + "', `email_address`='"
                + email
                + "' WHERE `username`='"
                + username
                + "'";
        session.setAttribute("email", email);
      } else if ((pw1.length() == 0) && (email.length() != 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `email_address`='"
                + email
                + "' WHERE `username`='"
                + username
                + "'";
        session.setAttribute("email", email);
      } else if ((pw1.length() != 0) && (email.length() == 0)) {
        strQuery =
            "UPDATE `twitter2012`.`users` SET `password`='"
                + pw1
                + "' WHERE `username`='"
                + username
                + "'";
      }
      Connection dbcon = null;
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      dbcon = DriverManager.getConnection(svr.getURL(), svr.getUN(), svr.getPW());
      st = dbcon.createStatement();
      st.executeUpdate(strQuery);
      session.setAttribute("ErrorMessage", "Details Changed");
      dbcon.close();
      session.setAttribute("ErrorMessage", "Details Changed");
      response.sendRedirect("home.jsp");
    } catch (Exception ex) {
      out.println(ex);
    }
  }