Pages

Saturday, 14 December 2013

ORACLE ORA-00600 ERROR SOLUTION

Some time we get a error from oracle, ORA-00600, and here is the solution for that.

PROBLEM :

ORA-00600: internal error code, arguments: [kcratr_nab_less_than_odr], [1],
[260], [12510], [12578], [], [], [], [], [], [], []



SOLUTION :

SQL> conn
SQL>sys as sysdba
SQL>password

SQL> Startup mount;

SQL>Show parameter control_files;

             Will give the list of the control files with full path of the files.

SQL>SELECT a.member,a.group#,b.status FROM v$logfile a, v$log b WHERE a.group#=b.group# AND b.status = 'CURRENT';

    Will give redo log file not down name of the redolog file with full path.

SQL>recover database using backup controlfile until cancel;

    Write the full Path of redolog file when asked.
    And hit enter.
    Will Give message "Log Applied. Media recovery complete."
   
SQL>alter database open resetlogs;
   
    Will give message "Database altered."

Now connect as your local user.

















IF YOU HAVE ANOTHER WAY TO SOLVE IT PLEASE SHARE IT AS COMMENT

Tuesday, 17 September 2013

ORACLE SELECT RECORD BETWEEN No1. TO No2.

In some cases we have to select the records from the database table between some specific value. Like I want to select record 1 TO 10 at first time 11 TO 20 at second time like this.

For this i have a solution with just a single query:

------------------------------------------------------------------------------------------------------------
SELECT * 
FROM (SELECT ALIAS1.*, ROW_NUMBER() OVER(ORDER BY column_name) AS MYROW FROM table_name ALIAS1 WHERE ALIAS1.column_name = where_clause) 
WHERE (MYROW BETWEEN 1 AND 10);
---------------------------------------------------------------------------------------------------------------------------------

EXPLANATION:-
In this Query Inner select query will select all the record from given table_name that satisfy the Inner WHERE clause and provide row number to each record and make it as table alias MYROW. Now outer WHERE clause will select 1 to 10 record from that record and display it as final output.


IF YOU HAVE BETTER WAY TO DO THIS THEN PLEASE PROVIDE IT AS COMMENT IT WILL VERY HELPFUL.

Friday, 6 September 2013

How To Create JAR File Step By Step

The JAR file format is a compressed format used primarily to distribute Java applications and libraries. It is built on the ZIP file format, and functions in a similar way; many files are compressed and packaged together in a single file, making it easy to distribute the files over a network. If you need to package a Java application or library, you can create a JAR file using the Java Development Kit (JDK) and your computer's command prompt.

Method One: Windows

1. Prepare your files. Place all the files you want to include in the JAR file inside a single folder. They will need to be referenced through a single command line, so specifying separate paths is not feasible.
2. Open the command prompt. This can be done by clicking on Start and then Run. Type "cmd" into the text box and click the "OK" button.

3. Navigate to the folder where you stored your files. By default, the command prompt will read "C:\>."
  • To navigate deeper into the hard drive, use the "change directory" command by typing "cd."
  • For example, if your files are stored at "C:\myfiles," then you should type "cd \myfiles."
4. Set the path to the directory of the JDK bin. You will need to run the jar.exe utility to create a JAR file, and that file is located in the bin directory.
  • Use the "path" command to specify the JDK bin directory. For example, if you installed JDK to the default location, you would type: "path c:\Program Files\Java\jdk1.5.0_09\bin"
  • If you aren't sure of the exact directory, navigate to it in Windows Explorer and take note of the directory's full path.
5. Create the JAR file. The format of the command line for creating the JAR file looks like this: "jar cf 'jar-file'.jar input-file(s)."
  • The "jar" portion refers to the jar.exe program, which compiles the JAR file.
  • The "c" option specifies that you want to create a JAR file
  • The "f" option means that you want to specify the filename.
  • The "jar-file" portion is where you should type the name that you want the file to have.
  • "Input-file(s)" is a space-separated list of all the files to be included in the JAR file.
  • For example, you might type "jar cf myjar manifest.txt myclass.class." This would create a JAR file with the filename "myjar.jar" which would include the files "manifest.txt" and "myclass.class."
  • If you add directories to the JAR file, the jar.exe utility will automatically add their contents.

Method Two: Mac

  1. Prepare your files. Put all the files you want to include in the JAR file inside a single folder.
    • Open a Terminal command prompt, and set it to the target directory where your JAR files are located.
  2. Compile the .java class. For example, compile HelloWorld.java with:
    • javac HelloWorld.java
    • This will produce a .class file needed for the JAR file.
  3. Create a manifest file. Save it using the extension .txt using the text editor and input the following:
    • Main-Class: HelloWorld (or whatever your file's name is)
  4. Create the JAR file using this code:
    • jar cfm HelloWorld.jar Manifest.txt HelloWorld.class
  5. Run the file:jar

Monday, 24 June 2013

Create XML file simple way

This is a simple program that display XML output in console. You can write it separate XML file. 

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

/**
* By : Anand Maheshwari
*/

public class CreateXMLFile2 {

    public static void main(String[] args) {
        DocumentBuilderFactory icFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder icBuilder;
        try {
            icBuilder = icFactory.newDocumentBuilder();
            Document doc = icBuilder.newDocument();
            Element mainRootElement = doc.createElementNS("http://crunchify.com/iCrunchCreateXMLDOM", "Companies");
            doc.appendChild(mainRootElement);

            // append child elements to root element
            mainRootElement.appendChild(getCompany(doc, "1", "Paypal", "Payment", "1000"));
            mainRootElement.appendChild(getCompany(doc, "2", "eBay", "Shopping", "2000"));
            mainRootElement.appendChild(getCompany(doc, "3", "Google", "Search", "3000"));

            // output DOM XML to console
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource(doc);
            StreamResult console = new StreamResult(System.out);
            transformer.transform(source, console);

            System.out.println("\nXML DOM Created Successfully..");

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

    private static Node getCompany(Document doc, String id, String name, String age, String role) {
        Element company = doc.createElement("Company");
        company.setAttribute("id", id);
        company.appendChild(getCompanyElements(doc, company, "Name", name));
        company.appendChild(getCompanyElements(doc, company, "Type", age));
        company.appendChild(getCompanyElements(doc, company, "Employees", role));
        return company;
    }

    // utility method to create text node
    private static Node getCompanyElements(Document doc, Element element, String name, String value) {
        Element node = doc.createElement(name);
        node.appendChild(doc.createTextNode(value));
        return node;
    }
}

Sunday, 23 June 2013

Read XML file using Java

Today i will so you how to read XML file data using Java so that you can further use for other purpose.

First of all you need xmlparserv2.jar  library file that is easily downloadable on net.

This is a XML file look like:

<student>
<person>
  <first>Anand</first>
  <last>Maheshwari</last>
  <age>22</age>
</person>
<person>
  <first>Vivek</first>
  <last>Shah</last>
  <age>21</age>
</person>
<person>
  <first>Steve</first>
  <last>Jobs</last>
  <age>40</age>
</person>
</student>

This is Java code for read XML :

package org.anand;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReadXMLFile {

    public static void main(String[] args) {
        try {
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(new File("D:/test.xml"));

            // Normalize text representation...
            doc.getDocumentElement().normalize();
            System.out.println("Root element of the doc is : "
                    + doc.getDocumentElement().getNodeName());
            NodeList listOfPersons = doc.getElementsByTagName("person");
            int totalPersons = listOfPersons.getLength();
            System.out.println("Total no of person : " + totalPersons);

            for (int i = 0; i < listOfPersons.getLength(); i++) {
                Node firstPersonNode = listOfPersons.item(i);
                if (firstPersonNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element firstPersonElement = (Element) firstPersonNode;

                    // ----------------
                    NodeList firstNameList = firstPersonElement
                            .getElementsByTagName("first");
                    Element firstNameElement = (Element) firstNameList.item(0);

                    NodeList textFNList = firstNameElement.getChildNodes();
                    System.out
                            .println("First Name : "
                                    + ((Node) textFNList.item(0))
                                            .getNodeValue().trim());

                    // ----------------
                    NodeList lastNameList = firstPersonElement
                            .getElementsByTagName("last");
                    Element lastNameElement = (Element) lastNameList.item(0);

                    NodeList textLNList = lastNameElement.getChildNodes();
                    System.out
                            .println("Last Name : "
                                    + ((Node) textLNList.item(0))
                                            .getNodeValue().trim());

                    // ----------------
                    NodeList ageList = firstPersonElement
                            .getElementsByTagName("age");
                    Element ageElement = (Element) ageList.item(0);

                    NodeList textAgeList = ageElement.getChildNodes();
                    System.out.println("Age : "
                            + ((Node) textAgeList.item(0)).getNodeValue()
                                    .trim());

                    // ---------------

                } // End of if clause
            }// end of for loop
        } catch (SAXParseException perr) {
            System.out.println("** parsing error " + ", line"
                    + perr.getLineNumber() + ", uri " + perr.getSystemId());
            System.out.println(" " + perr.getMessage());
        } catch (SAXException se) {
            Exception x = se.getException();
            ((x == null) ? se : x).printStackTrace();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }// end of main
} // end of class

Output Of This program :

Root element of the doc is : student
Total no of person : 3
First Name : Anand
Last Name : Maheshwari
Age : 22
First Name : Vivek
Last Name : Shah
Age : 21
First Name : Steve
Last Name : Jobs
Age : 40

Saturday, 15 June 2013

String To Int and Int To String Conversion In Java

       HOW TO CONVERT STRING TO INTEGER AND INTEGER TO STRING IN JAVA

String to Integer Conversion in Java

1 ) By using Integer.parseInt( String str) method.

This is preferred way of converting it, extremely easy and most flexible way of converting String to Integer.

Example :
      // using Integer.parseInt()
      int i = Integer.parseInt("12345");
      System.out.println(i);

This method will throw NumberFormatException if string provided is not a proper number. Same technique can be used to convert data type like float and double to String in Java. Java API provides static methods like Float.parseFloat() and Double.parseDouble() to perform data type conversion.

2 ) Second way, using Integer.valueOf().

Example :
      //How to convert number string = "000000081" into Integer value = 81
      int i = Integer.valueOf("00000081");
      System.out.println(i);

It will ignore the leading zeros and convert the string into int. This method also throws NumberFormatException.

Integer to String Conversion

1 ) Int to String in java using "+" operator
It is a simplest way to convert. Just use "+" operator with int value.

Example
      String price = ""+123;

2 ) Use String.valueOf() method which is static method to convert any integer value to String. In fact String.valueOf(0 method is overloaded to accept almost all primitive type so you can use it convert char, double, float, or any other data type into String.

Example :
      String price = String.valueOf(123);

3 ) Using String.format()
This is a new way of converting an int primitive to String object and introduced in JDK 1.5 along-with several other important features like Enum, Generics and Variable arguments methods. String.format() is even more powerful and can be used in variety of way to format String in Java.

Example :
      String price = String.format("%d",123);

 

Friday, 22 March 2013

Java Servlet + JSP + MySQL Connectivity Example


This tutorial include one login page when user login successfully then one page with customer list appear with id as link when user click on that link the address of that user will display on new jsp page.







Table need in MYSQL.

TBLLOGIN - Contain Login user data (username,password)
TBLCUSTOMER - Contain list of customer. (cid,cname)
TBLADDRESS - Contain Address of the customer (cid,address)

Now First of all We create LOGIN.JSP page in Eclipse IDE.

login.jsp
                             

<body>
    <form name="loginPage" action="Login" method="post">
        <table align="center">
            <tr>
                <td align="right">User Name :</td>
                <td align="right"><input type="text" name="name" id="txtName"></td>
            </tr>
            <tr>
                <td align="right">Password :</td>
                <td align="right"><input type="password" name="pass" id="txtPass"></td>
            </tr>
            <tr>
                <td><input type="submit" value="Login"></td>
                <td></td>
            </tr>
        </table>
    </form>
</body>


When User submit the page Login Servlet in called...

Login.java 
Code for doPost()

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
        String uname = request.getParameter("name");
        String pass = request.getParameter("pass");
       
        List custData = new ArrayList();
       
        DatabaseConnection dbConn = new DatabaseConnection();
        Connection conn = dbConn.mySqlConnection();
        try{
            int count = 0;
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT uname,pass FROM tbllogin WHERE                   uname        ='"+uname+"' AND pass='"+pass+"'");
            while(rs.next()){
                count++;
            }
           
            if(count != 0){
               
                rs = stmt.executeQuery("SELECT CID,CNAME FROM tblcustomer");
               
                while(rs.next()){
                    custData.add(rs.getInt("CID"));
                    custData.add(rs.getString("CNAME"));
                }
               
                request.setAttribute("cdata",custData);
                request.getRequestDispatcher("customer_list.jsp").forward(request, response);
            }
            else{
                System.out.println("Error In connection...");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }


We use connection class for connecting with MySQL database.

DatabaseConnection.java class


import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class DatabaseConnection {

    Connection conn = null;
    String url;
    String driver;
    String userName;
    String password;

    public Connection mySqlConnection() {

        url = "jdbc:mysql://localhost:3306/test";
        driver = "com.mysql.jdbc.Driver";
        userName = "root";
        password = "root";

        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, userName, password);
            System.out.println("Connected.");
           
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }
}


Now After Login Customer Detail page will load with all customer list in table.
customer_list.jsp

                             
<script type="text/javascript">
    function getAddress(id) {
        alert(id);
        document.forms[0].action="/TestDemo/AddressDetail?cid="+id;
        document.forms[0].submit();

    }
</script>

<body>
    <form name="custData" method="post">
        <table border="1" align="center">
            <tr>
                <td>CID</td>
                <td>CNAME</td>
            </tr>
            <%
                Iterator itr;
            %>
            <%
                List data = (List) request.getAttribute("cdata");
                for (itr = data.iterator(); itr.hasNext();) {
            %>
            <tr>
                <td><input type="text" value=<%=itr.next()%>
                    onclick="getAddress(this.value);" style="cursor: pointer;" /></td>
                <td><%=itr.next()%></td>
            </tr>
            <%
                }
            %>
        </table>
    </form>
</body>


When user click on ID field of table address of that customer will display on other page.
call AddressDetail.java servlet when user click on id field of the table.

protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
   
        int id = Integer.parseInt(request.getParameter("cid"));

        DatabaseConnection dbConn = new DatabaseConnection();
        Connection conn = dbConn.mySqlConnection();
        String address = null;
        try {
            int count = 0;
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt
                    .executeQuery("SELECT address FROM tbladdress WHERE cid = "+id);
            while (rs.next()) {
                address = rs.getString("address");
            }

            if (address != null) {
                request.setAttribute("address", address);
                request.getRequestDispatcher("cust_address.jsp").forward(
                        request, response);
            } else {
                System.out.println("Error In connection...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


Now finally address of the customer display on JSP page.
cust_address.jsp


<p>Address Of Selected Client : ${address}</p>