public static void main(String[] args) throws SQLException {
   // declare a connection by using Connection interface
   Connection connection = null;
   /* Create string of connection url within specified format with machine
   name, port number and database name. Here machine name id localhost
   and database name is mahendra. */
   String connectionURL = "jdbc:mysql://localhost:3306/mahendra";
   /*declare a resultSet that works as a table resulted by execute a specified
   sql query. */
   ResultSet rs = null;
   // Declare prepare statement.
   PreparedStatement psmnt = null;
   // declare FileInputStream object to store binary stream of given image.
   FileInputStream fis;
   try {
     // Load JDBC driver "com.mysql.jdbc.Driver"
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     /* Create a connection by using getConnection() method that takes
     parameters of string type connection url, user name and password to
     connect to database. */
     connection = DriverManager.getConnection(connectionURL, "root", "root");
     // create a file object for image by specifying full path of image as parameter.
     File image = new File("C:/image.jpg");
     /* prepareStatement() is used for create statement object that is
     used for sending sql statements to the specified database. */
     psmnt =
         connection.prepareStatement(
             "insert into save_image(name, city, image, Phone) " + "values(?,?,?,?)");
     psmnt.setString(1, "mahendra");
     psmnt.setString(2, "Delhi");
     psmnt.setString(4, "123456");
     fis = new FileInputStream(image);
     psmnt.setBinaryStream(3, (InputStream) fis, (int) (image.length()));
     /* executeUpdate() method execute specified sql query. Here this query
     insert data and image from specified address. */
     int s = psmnt.executeUpdate();
     if (s > 0) {
       System.out.println("Uploaded successfully !");
     } else {
       System.out.println("unsucessfull to upload image.");
     }
   } // catch if found any exception during rum time.
   catch (Exception ex) {
     System.out.println("Found some error : " + ex);
   } finally {
     // close all the connections.
     connection.close();
     psmnt.close();
   }
 }
Пример #2
0
  public static void main(String argv[]) {
    Connection con = null;
    PreparedStatement pstmt = null;
    InputStream fin = null;
    String url = "jdbc:oracle:thin:@localhost:1521:XE";
    String userid = "hr1";
    String passwd = "123456";
    String picName[] = {"iconPet29.jpg", "iconPet30.png"};
    int[] picPetId = {29, 30};
    int rowsUpdated = 0;
    try {
      con = DriverManager.getConnection(url, userid, passwd);

      for (int i = 0; i < picName.length; i++) {
        File pic = new File("WebContent/images", picName[i]); // �۹���|- picFrom
        // ������|- Ĵ�p:
        // File pic = new File("x:\\aa\\bb\\picFrom", picName);
        long flen = pic.length();
        fin = new FileInputStream(pic);
        pstmt = con.prepareStatement("UPDATE PET SET icon = ? WHERE ID = ?");
        pstmt.setBinaryStream(1, fin, (int) flen); // void
        // pstmt.setBinaryStream(int
        // parameterIndex,
        // InputStream x,
        // int length)
        // throws
        // SQLException
        pstmt.setInt(2, picPetId[i]);
        rowsUpdated += pstmt.executeUpdate();
      }

      System.out.print("Changed " + rowsUpdated);

      if (1 == rowsUpdated) System.out.println(" row.");
      else System.out.println(" rows.");

      fin.close();
      pstmt.close();

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        con.close();
      } catch (SQLException e) {
      }
    }
  }
  public static void add(String a, String b, File x, String s) throws Exception {
    fis = new FileInputStream(x);

    pa.setString(1, "" + dt);
    pa.setInt(2, pid);
    pa.setString(3, pfnm);
    pa.setString(4, pmnm);
    pa.setString(5, plnm);
    pa.setString(6, gen);
    pa.setInt(7, age);
    pa.setString(8, wt);
    pa.setString(9, a);
    pa.setString(10, cno);
    pa.setString(11, dnm);
    pa.setString(12, b);
    pa.setString(13, dig);
    pa.setInt(14, fee);
    pa.setString(15, bg);
    pa.setString(17, s);
    pa.setBinaryStream(16, (InputStream) fis, (int) (x.length()));

    pa.executeUpdate();
  }
  public static void mod(File x, String s) throws Exception {

    try {
      System.out.println(x);
      fis = new FileInputStream(x);
      // tmp=con.prepareStatement("update patient set
      // dt=?,pfnm=?,pmnm=?,plnm=?,gen=?,age=?,wt=?,addr=?,cno=?,dnnm=?,sym=?,dig=?,fee=? where
      // pid=1");
      tmp =
          con.prepareStatement(
              "update patient set dt=?,pfnm=?,pmnm=?,plnm=?,gen=?,age=?,wt=?,addr=?,cno=?,dnm=?,sym=?,dig=?,fee=?,bg=?,i=?,path=? where pid="
                  + pid);
      // tmp.setString(1,pfnm);
      tmp.setString(1, "" + dt);
      tmp.setString(2, pfnm);
      tmp.setString(3, pmnm);
      tmp.setString(4, plnm);
      tmp.setString(5, gen);
      tmp.setInt(6, age);
      tmp.setString(7, wt);
      tmp.setString(8, addr);
      tmp.setString(9, cno);
      tmp.setString(10, dnm);
      tmp.setString(11, sym);
      tmp.setString(12, dig);
      tmp.setInt(13, fee);
      tmp.setString(14, bg);

      tmp.setString(16, s);
      tmp.setBinaryStream(15, (InputStream) fis, (int) (x.length()));

      tmp.executeUpdate();
    } catch (Exception ee) {
      System.out.println("mod123 " + ee);
    }
  }
Пример #5
0
  /**
   * Takes a vector full of property lists and generates a report.
   *
   * @param args Command line arguments. args[0] should be the config filename.
   */
  public static void main(String[] args) {
    // Load the database properties from properties file
    Properties properties = new Properties();

    // Load config file
    String configFile = null;
    if (args.length > 0) configFile = args[0];

    try {
      if (configFile == null) {
        System.out.println("Database config file not set.");
        return;
      } else properties.load(new FileInputStream(configFile));
    } catch (IOException e) {
      System.out.println("Error opening config file.");
    }

    String url = properties.getProperty("databaseUrl");
    String username = properties.getProperty("username");
    String password = properties.getProperty("password");
    String dir = System.getProperty("user.dir"); // Current working directory
    Connection con = null;

    // Try to open file containing javac output
    String output = "";
    try {
      BufferedReader outputReader = new BufferedReader(new FileReader(dir + "/CompileOut.txt"));

      while (outputReader.ready()) output += outputReader.readLine() + '\n';

      // Close file
      outputReader.close();
    } catch (FileNotFoundException e) {
      System.out.println("Error opening compilation output file.");
      return;
    } catch (IOException e) {
      System.out.println("I/O Exception Occured.");
      return;
    }

    boolean hasDriver = false;
    // Create class for the driver
    try {
      Class.forName("com.mysql.jdbc.Driver");
      hasDriver = true;
    } catch (Exception e) {
      System.out.println("Failed to load MySQL JDBC driver class.");
    }

    // Create connection to database if the driver was found
    if (hasDriver) {
      try {
        con = DriverManager.getConnection(url, username, password);
      } catch (SQLException e) {
        System.out.println("Couldn't get connection!");
      }
    }

    // Check that a connection was made
    if (con != null) {
      long userEventId = -1;

      // Store results from the report into the database
      try {
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/userId.txt")); // Read userId.txt to get userId
        String userId = rd.readLine(); // Store userId from text file
        rd.close();

        // Insert the report into the table and get the auto_increment id for it
        Statement stmt = con.createStatement();
        stmt.executeUpdate("INSERT INTO userEvents (userId) VALUES ('" + userId + "')");
        ResultSet result = stmt.getGeneratedKeys();
        result.next();
        userEventId = result.getLong(1);

        // Close the statement
        stmt.close();

        // Prepare statement for adding the compilation error to the userEvent
        PreparedStatement compErrorPrepStmt =
            con.prepareStatement(
                "INSERT INTO userEventCompilationErrors(userEventId, output) VALUES (?, ?)");

        // Insert userEventId and docletId into the database
        compErrorPrepStmt.setLong(1, userEventId);
        compErrorPrepStmt.setString(2, output);
        compErrorPrepStmt.executeUpdate();

        // Close the prepare statements
        compErrorPrepStmt.close();
      } catch (Exception e) {
        System.out.println("Exception Occurred");
        System.out.println(e);
      }

      // Store the java files for the report
      try {
        // Prepare statement for storing files
        PreparedStatement filePrepStmt =
            con.prepareStatement(
                "INSERT INTO files(userEventId, filename, contents) VALUES ("
                    + userEventId
                    + ", ?, ?)");

        // Get the list of files from source.txt
        BufferedReader rd =
            new BufferedReader(
                new FileReader(dir + "/source.txt")); // Read userId.txt to get userId
        while (rd.ready()) {
          String filename = rd.readLine(); // Store userId from text file
          // Remove the "src/" from the beginning to get the real file name
          String realname = filename.substring(4);
          filePrepStmt.setString(1, realname);

          // Read in the contents of the files
          String contents = "";
          File javaFile = new File(dir + "/" + filename);
          int length = (int) javaFile.length();

          // Add parameter for file contents to the prepared statement and execute it
          filePrepStmt.setCharacterStream(2, new BufferedReader(new FileReader(javaFile)), length);
          filePrepStmt.executeUpdate();
        }
        rd.close();
      } catch (IOException e) {
        System.err.println("I/O Exception Occured.");
      } catch (SQLException e) {
        System.err.println("SQL Exception Occured.");
      }
    }
  }
  /**
   * Compare the checksums of the hdfs file as well as the local copied file.
   *
   * @author [email protected]
   * @date Fri Jan 27 06:06:00 2012
   */
  boolean compareChecksums(FileSystem fs, Path p, String sFsPath) {
    try {
      // get hdfs file info
      FileStatus stat = fs.getFileStatus(p);

      // get HDFS checksum
      FileChecksum ck = fs.getFileChecksum(p);
      String sCk, sCkShort;
      if (ck == null) {
        sCk = sCkShort = "<null>";
      } else {
        sCk = ck.toString();
        sCkShort = sCk.replaceAll("^.*:", "");
      }

      // System.out.println(p.toUri().getPath() + " len=" + stat.getLen()
      // + " " + stat.getOwner() + "/" + stat.getGroup()
      // + " checksum=" + sCk);

      // find the local file
      File fLocal = new File(sFsPath);
      if (!fLocal.exists()) {
        System.out.println("CHECKSUM-ERROR: file does not exist: " + sFsPath);
        return false;
      }
      if (!fLocal.isFile()) {
        System.out.println("CHECKSUM-ERROR: path is not a file: " + sFsPath);
        return false;
      }
      if (stat.getLen() != fLocal.length()) {
        System.out.println(
            "CHECKSUM-ERROR: length mismatch: "
                + sFsPath
                + " hdfslen="
                + stat.getLen()
                + " fslen="
                + fLocal.length());
        return false;
      }

      // get local fs checksum
      FileChecksum ckLocal = getLocalFileChecksum(sFsPath);
      if (ckLocal == null) {
        System.out.println("ERROR Failed to get checksum for local file " + sFsPath);
        return false;
      }

      // compare checksums as a string, after stripping the
      // algorithm name from the beginning
      String sCkLocal = ckLocal.toString();
      String sCkLocalShort = sCkLocal.replaceAll("^.*:", "");

      if (false == sCkShort.equals(sCkLocalShort)) {
        System.out.println(
            "CHECKSUM-ERROR: checksum mismatch: "
                + sFsPath
                + "\nhdfs = "
                + sCk
                + "\nlocal= "
                + sCkLocal);
        return false;
      }

      return true;
    } catch (IOException e) {
      System.out.println("CHECKSUM-ERROR: " + sFsPath + " exception " + e.toString());
    }

    return false;
  }