JAVA N WEB TECH SYLLABUS

Thursday, December 23, 2010

Program to insert new name and age information entered by the user into the database.

cust.html


    <html>

    <body>
    Enter the Customer details to add a  record in Customer table
    <br>
    <form action="http://192.168.8.3/naveen/cust.php" method="get">
    Name:<input type="text" name="uname">
    Age:<input type="text" name="uage">
    <input type="submit" >
    <input type="reset">
    </form>

    
    </body>
    </html>


output:
-----------------------------------------------------------------------------------------------------------------------------------
Enter the Customer details to add a record in Customer table

Name: Age:
-------------------------------------------------------------------------------------------------------------
cust.php


             <?
                $name=$_GET["uname"];
                $age=$_GET["uage"];
                $query1="Insert into customer values('$name',$age)";
                echo "$query1";
                
                
                // connect to the mysql server on localhost 
                $mysql = mysql_connect("192.168.8.3", "naveen", "a") 
                    or die("could not connect to mysql"); 

                    
                // execute the MySQL query, grab the result in $result 
                $result1 = mysql_db_query("naveen", $query1) 
                    or die("query failed  ");
                    $query2="select * from customer";
                echo "$query2";
                $result = mysql_db_query("studentinfo", $query2) 
                    or die("query failed  ");
                

            ?> 
            <html> 
            <head> 
            <title>PHP and MySQL</title> 
            </head> 
            <body bgcolor="CYAN"> 
            We Added the Record: 
            <hr> 
            We found <b> <?echo mysql_num_rows($result); ?></b> rows. 

            <h3>Query result</h3> 
            <br>
            <table border=2>
            <tr>
                
                <td>NAME</td>
                <td>AGE</td>
                
            </tr>

                
             <?
                //loop through each row 
                while ($array = mysql_fetch_row($result)) 
                { 
                    echo "<tr>";

                    echo "<td>$array[0]</td>";
                    echo "<td>$array[1]</td>";
                    
                echo "</tr>";
             
                } 
            ?> 
            </table>
            </body> 
            </html> 
             <?
                // we are all done, so close the MySQL connection 
                mysql_close($mysql); 
            ?> 
-------------------------------------------------------------------------------------------------------------
OUTPUT:
Insert into customer values('naveen11',27)   
We Added the Record:
We found rows.

Query result select * from customer


NAME AGE
jhonny 22
bravo 22
naveen 27
xyz 27
abc27

Program to display the current contents of the table in a database.

display.php   

    <?
        // connect to the mysql server on localhost
        $mysql = mysql_connect("192.168.8.3", "naveen", "a")
            or die("could not connect to mysql");

        // execute the MySQL query, grab the result in $result
        $result = mysql_db_query("naveen", "SELECT * FROM student")
            or die("query failed  ");

    ?>
    <html>
    <head>
    <title>PHP and MySQL</title>
    </head>
    <body bgcolor="CYAN">
    We executed: <b> SELECT * FROM student</b>
    <hr>
    We found <b><?echo mysql_num_rows($result); ?></b> rows.

    <h3>Query result</h3>
    <br>
    <table border=2>
    <tr>
   <td>USN</td>
   <td>NAME</td>
   <td>BRANCH</td>
   <td>SEM</td>
   <td>CGPA</td>
    </tr>

 
    <?
        //loop through each row
        while ($array = mysql_fetch_row($result))
   {
            echo "<tr>";

   echo "<td>$array[0]</td>";
   echo "<td>$array[1]</td>";
   echo "<td>$array[2]</td>";
   echo "<td>$array[3]</td>";
   echo "<td>$array[4]</td>";
   echo "</tr>";
    
   }
    ?>
    </table>
    </body>
    </html>
    <?
        // we are all done, so close the MySQL connection
        mysql_close($mysql);
    ?>
OUT PUT:
We executed: SELECT * FROM student
We found 7 rows.

Query result


USN NAME BRANCH SEM CGPA
2sd02is006 jhon cse 7 8.75
2sd02is007 jackie ec 5 7.75
2sd02is008 tom ee 5 6.75
2sd02is008 jerry ise 7 7.77
2sd02is015 ford ise 5 5.55
ytyutyu ee ee 2 5.55
2sd05is099 nnnnn ise 7 9.99

Program to keep track of the number of visitors, visited the web page and display the counter with proper headings.

count.html
<html>
<body>
To know the no of times the web page Count.php is viewed <a href="http://192.168.8.3/naveen/count.php">Click Here</a>
</body>
</html>

count.php

<?

$filename = 'c.txt';

if (file_exists($filename))
    {
        $count = file('c.txt'); //read all the lines from the file c.txt and store it in array
        $count[0] ++;//increment the first line
        $fp = fopen("c.txt", "w"); //open c.txt in write mode
        fputs ($fp, "$count[0]"); //put the updated value in c.txt 
        fclose ($fp);
        echo "No of vistors vistin the pages is $count[0]";
    }
?>
Note:For this code u hav to create c.txt in u r webcontainer
go to u r web contain
cd /var/www/html/<usn>
vi c.txt
enter the value 0 and save it
change the permission of c.txt to 777
access the html to see the no of times the page is visited.

Program to accept UNIX command from a HTML form and display the output of the command executed.

cmd.html
<html>
<body>
Enter the valid Linux command :
<form action="http://192.168.8.3/naveen/cmd.php" method ="get">
<input type="text" name="cmd">
<input type="submit">
</form>
</body>
</html>

cmd.php

<html>
<body>
<? $cmd=$_GET["cmd"];?>
The output of the command <? echo "$cmd"; ?> is:
<br>
<? $s=system($cmd); 
echo "$s";
?>
</body>
</html>

Note : if we use exec($cmd) it will only print the last line of the output command so its better to use
system($cmd); which will print all the lines of the output of the command.

A Simple PHP

<html>
<body>
<?
echo "Welcome To My First PHP Page"<br>";

$name="naveen";
$sem=7;
$cgpa=7.77;
$cgpa2=$cgpa*10;
echo $name;
echo "<br>";
echo $sem;
echo "<br>";
echo $cgpa;
echo "<br>";
echo $cgpa2;


?>
</body>
</html>

Wednesday, December 22, 2010

JDBC ResultSet MetaData

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

public class MyResultSetMetaData {
    public static void main(String[] args) throws Exception {
        Connection conn = getHSQLConnection();
        Statement st = conn.createStatement();
      
      
        st = conn.createStatement();
        ResultSet rs = st.executeQuery("SELECT * FROM student");
      
        ResultSetMetaData rsMetaData = rs.getMetaData();
      
        int numberOfColumns = rsMetaData.getColumnCount();
        System.out.println("resultSet MetaData column Count=" + numberOfColumns);
      
        String TableName = rsMetaData.getTableName(1);
        System.out.println("resultSet MetaData TableName=" + TableName);
      
      
      
        String ColumnLabel = rsMetaData.getColumnLabel(1);
        System.out.println("resultSet MetaData column Label 1=" + ColumnLabel);
      
        String ColumnLabe2 = rsMetaData.getColumnLabel(2);
        System.out.println("resultSet MetaData column Label 2=" + ColumnLabe2);
      
      
        rs.close();
        st.close();
        conn.close();
    }
  
    private static Connection getHSQLConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost/studentinfo";
        return DriverManager.getConnection(url, "root", "root");
    }
}
output


resultSet MetaData column Count=5
resultSet MetaData TableName=student
resultSet MetaData column Label 1=usn
resultSet MetaData column Label 2=name

JDBC Database MetaData

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

public class Main {
    public static void main(String[] args) throws Exception {
        Connection conn = getConnection();
      
        DatabaseMetaData mtdt = conn.getMetaData();
        System.out.println("URL in use: " + mtdt.getURL());
        System.out.println("User name: " + mtdt.getUserName());
        System.out.println("DBMS name: " + mtdt.getDatabaseProductName());
        System.out.println("DBMS version: " + mtdt.getDatabaseProductVersion());
        System.out.println("Driver name: " + mtdt.getDriverName());
        System.out.println("Driver version: " + mtdt.getDriverVersion());
        System.out.println("supp. SQL Keywords: " + mtdt.getSQLKeywords());
      
      
        conn.close();
    }
  
    private static Connection getConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost/studentinfo";
      
        return DriverManager.getConnection(url, "root", "root");
    }
}
output


URL in use: jdbc:mysql://localhost/studentinfo
User name: root@localhost
DBMS name: MySQL
DBMS version: 5.0.27-community-nt
Driver name: MySQL-AB JDBC Driver
Driver version: mysql-connector-java-5.0.5 ( $Date: 2007-03-01 00:01:06 +0100 (Thu, 01 Mar 2007) $, $Revision: 6329 $ )

Using Prepared Statement

In this code we r makin use of the PreparedStatement for displayin a particular student record from student table


import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * Display.java
 *
 * Created on December 14, 2010, 9:25 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author Naveen
 */
public class Display {
  
    /** Creates a new instance of Display */
    public Display() {
    }
    public static void main(String args[]) {
        PreparedStatement pstmt=null;
        Connection conn = null;
        ResultSet rs=null;
      
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        String url="jdbc:mysql://localhost/studentinfo";
        String userName="root";
        String password="root";
        try {
          
            conn=DriverManager.getConnection(url,userName,password);
          
        }
      
        catch (SQLException ex) {
            System.out.println("Unable to Connect to Database");
        }
      
        try {
          
            String query="select * from student where cgpa=? and sem =?";
            pstmt=conn.prepareStatement(query);
          
            pstmt.setFloat(1,8.75f);
            pstmt.setInt(2,7);
            rs =pstmt.executeQuery();
            while(rs.next()) {
                System.out.print(rs.getString(1)+"\t");
                System.out.print(rs.getString(2)+"\t");
                System.out.print(rs.getString(3)+"\t");
              
                System.out.print(rs.getInt(4)+"\t");
                System.out.print(rs.getFloat(5)+"\t");
            }
          
          
        } catch (SQLException ex) {
            System.out.println("Unable to create Statment");
        }
      
      
      
      
      
    }
}

Displaying all the records from Student table

Here in this code we r displaying all the  student records from student table.In this example code we are makin use of jdbc driver type 4 provided by mysql.



import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * Display.java
 *
 * Created on December 14, 2010, 9:25 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */


/**
 *
 * @author Naveen
 */
public class Display2 {
    
    /** Creates a new instance of Display */
    public Display2() {
    }
    public static void main(String args[]) {
        
        Connection conn = null;
        ResultSet rs=null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        String url="jdbc:mysql://localhost/studentinfo";
        String userName="root";
        String password="root";
        try {
            
            conn=DriverManager.getConnection(url,userName,password);
            
        }
        
        catch (SQLException ex) {
            System.out.println("Unable to Connect to Database");
        }
        
        try {
            
            String query="Select * from student" ;
            stmt=conn.createStatement();
            
            
            rs= stmt.executeQuery(query);
            while(rs.next()) {
                System.out.print(rs.getString("usn")+"\t");
                System.out.print(rs.getString(2)+"\t");
                System.out.print(rs.getString(3)+"\t");
                
                System.out.print(rs.getInt(4)+"\t");
                System.out.println(rs.getFloat(5)+"\t");
            }
            
            
            
            
        } catch (SQLException ex) {
            System.out.println("Unable to create Statment");
        }
        
        
        
        
        
    }
}

The JDBC Process

Here in this code we r inserting a student record into a student table.In this example code we are makin use of jdbc driver type 4 provided by mysql.

import java.io.DataInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * DemoJdbc.java
 *
 * Created on December 13, 2010, 10:23 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author Naveen
 */
public class DemoJdbc {
  
    /** Creates a new instance of DemoJdbc */
    public DemoJdbc() {
      
    }
    public static void main(String args[]) {
        DataInputStream din=new DataInputStream(System.in);
        Connection conn = null;
        Statement stmt = null;
      
        try {
            System.out.println("Enter the data usn,name,branch,sem,cgpa");
            String usn=din.readLine();
            String name=din.readLine();
            String branch=din.readLine();
            String sem=din.readLine();
            String cgpa=din.readLine();
            try {
              
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                System.out.println("Unable to Load Class");
            }
            String url="jdbc:mysql://localhost/studentinfo";
            String userName="root";
            String password="root";
            try {
              
                conn=DriverManager.getConnection(url,userName,password);
              
            }
          
            catch (SQLException ex) {
                System.out.println("Unable to Connect to Database");
            }
            try {
              
                stmt=conn.createStatement();
            } catch (SQLException ex) {
                System.out.println("Unable to create Statment");
            }
          
            boolean sucessful = false;
            try {
              
                String query="Insert into student values (" +
                        "'"+usn+"',"+
                        "'"+name+"',"+
                        "'"+branch+"',"+
                        sem+","+cgpa+")";
              
                System.out.println("\nQuery Framed=="+query);
                sucessful = stmt.execute(query);
                System.out.println("Query executed sucessfully");
              
              
            } catch (SQLException ex) {
                System.out.println("Query  not executed ");
            }
          
          
          
          
        } catch (IOException ex) {
            System.out.println("Unable to read data from keyboard");
        } finally {
            try {
                conn.close();
            } catch (SQLException ex) {
                System.out.println("Unable to close Connection");
            }
        }
      
      
    }
}

Tuesday, December 14, 2010

Difference between String s = "abc"; vs String s2 = new String("abc");

/*
 * NewMain.java
 *
 * Created on December 14, 2010, 11:43 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

/**
 *
 * @author Naveen
 */
public class NewMain {
  
    /** Creates a new instance of NewMain */
    public NewMain() {
    }
  
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String s1="abc";
        String s2="abc";
        String s3=new String("abc");


Naveen Mirajkar December 15 at 12:16am
/*
* NewMain.java
*
* Created on December 14, 2010, 11:43 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

/**
*
* @author Naveen
*/
public class NewMain {

/** Creates a new instance of NewMain */
public NewMain() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String s1="abc";
String s2="abc";
/*
for these 2 above line in first for s1 runtime will create a new object and it is referenced by s1
4 nd line
already sequence of char "abc" is in mem pool at runtime so the java interpretor will not create a new object but to already exsisting object referred by s1 is assigned to s2
thats why when u use s1==s2 v use == wrt object to chech weather they are same or not wrt to memloc and their hashcode


in the line s3=new String("abc")
the runtime will create a new object in heap havin seq of chars "abc"

but
it has its own mem addr diff from s1 n s2
so if u use
s1==s3
it is false


but
s1.equals(s3)
is true coz v checkin the char seqncs in both the objs which r same

ok
i hope u got it..........*/




        String s4=s1;
        if(s1==s4) {
            System.out.println("Hi0");
        }
        if(s1.equals(s4)) {
            System.out.println("Hi00");
        }
      
        if(s1==s2) {
            System.out.println("Hi");
        }
        if(s1==s3) {
            System.out.println("Hello");
        }
        if(s1.equals(s2)) {
            System.out.println("Hi1");
        }
        if(s1.equals(s3)) {
            System.out.println("Hi2");
        }
      
      
      
        System.out.println(s1==s2); //true
        System.out.println(s1==s3); //false diff object identity
        System.out.println(s1.equals(s2)); //true
        System.out.println(s1.equals(s3)); //true
      
        System.out.println(System.identityHashCode(s1)); //they are
        System.out.println(System.identityHashCode(s2)); //the same object
        System.out.println(System.identityHashCode(s3)); //diff  object
      
      
      
    }
}
output

Hi0
Hi00
Hi
Hi1
Hi2
true
false
true
true
4072869
4072869
1671711