Tuesday, September 1, 2015

Query String , ViewState , Session

Query String : to send information through URL

 Response.Redirect("Default3.aspx?val1=ass&val2=" & TextBox1.Text)

The query string cannot be viewed as well as the current page URL will be shown even after the redirection of web page.

        Server.Transfer("Default3.aspx?val1=ass&val2=" & TextBox1.Text)


To retrieve information from URL
 Response.Write(Request.QueryString("val1") + "  " + Request.QueryString("val2"))



Viewstate : syntax

 increment of  viewstate  value which can be saved even after the page postback.
           ViewState("cnt") = ViewState("cnt") + 1 


Session : syntax


' Check in Page load of  a webpage

if  textbox1.text= "vamsi" then
Session("username")=textbox1.text 
response.redirect("homepage.aspx")
endif

'below code with in homepage.aspx  at pageload even


Response.write("Welcome " + Session("username"))


'Checking of user name on each webpage at pageload event

'the below code should check whether the username is hari or not. if its hari its move on to the else part or it will redirect the page which created by the user "errpage.aspx" 

' the thing is it may not allow the current page to the unauthorised user

If Session("username") <> "hari" Then

            Response.Redirect("errpage.aspx")


        Else

            Response.Write(Request.QueryString("val1") + "  " + Request.QueryString("val2"))

        End If






Friday, August 21, 2015

Regular Expression control - Different Expressions

links 


BThere are 3 types of brackets used in regular expression
Square brackets “[“and Curly “{“ brackets.
Square brackets specify the character which needs to be matched while curly brackets specify how many characters. “(“ for grouping.
We will understand the same as we move ahead in this article.
Ccaret “^” marks the start of a pattern.^ may appear at the beginning of a pattern to require the match to occur at the very beginning of a line. For example, ^xyz matches xyz123 but not 123xyz. 
DDollar “$” marks the end of a pattern.$ may appear at the end of a pattern to require the match to occur at the very end of a line. For example, pqr$ matches 123pqr but not pqr123. 


Caret (^) and dollar sign ($) indicate the pattern to the beginning or end of the string being searched.The two anchors may be combined. For example, ^pqr$ matches only pqr. Any characters after or before it will make the pattern invalid.  

Let’s start with the first validation, enter character which exists between a-g?

[a-g]

Enter characters between [a-g] with length of 3?

[a-g]{3}

Enter characters between [a-g] with maximum 3 characters and minimum 1 character?

[a-g]{1,3}

How can I validate data with 8 digit fix numeric format like 91230456, 01237648 etc?

^[0-9]{8}$

How to validate numeric data with minimum length of 3 and maximum of 7, ex -123, 1274667, 87654?

We need to just tweak the first validation with adding a comma and defining the minimum and maximum length inside curly brackets.
^[0-9]{3,7}$



Validate invoice numbers which have formats like LJI1020, the first 3 characters are alphabets and remaining is 8 length number?

First 3 character validation
^[a-z]{3}
8 length number validation
[0-9]{8}
Now butting the whole thing together.
^[a-z]{3}[0-9]{7}$

Check for format INV190203 or inv820830, with first 3 characters alphabets case insensitive and remaining 8 length numeric?

In the previous question the regex validator will only validate first 3 characters of the invoice number if it is in small letters. If you put capital letters it will show as invalid. To ensure that the first 3 letters are case insensitive we need to use ^[a-zA-Z]{3} for character validation.
Below is how the complete regex validation looks like.
^[a-zA-Z]{3}[0-9]{7}$



Validate numbers are between 0 to 25

^(([0-9])|([0-1][0-9])|([0-2][0-5]))$

Validation for only numbers
"^[0-9]*$" 


To get MM/DD/YYYY use the following regex pattern.
^([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[- / .](1[9][0-9][0-9]|2[0][0-9][0-9])$
And finally to get YYYY/MM/DD use the following regex pattern.
^(1[9][0-9][0-9]|2[0][0-9][0-9])[- / .]([1-9]|0[1-9]|1[0-2])[- / .]([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])$

Short cuts

You can also use the below common shortcut commands to shorten your regex validation.
Actual commandsShortcuts
[0-9]\d
[a-z][0-9][_]\w
O or more occurrences*
1 or more occurrences+
0 or 1 occurrence?



Monday, August 17, 2015

Compare Validator Example

Design View
-------------------------
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
        <title>CompareValidator example: how to use CompareValidator control in asp.net</title>
    </head>
   
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:Label ID="Label1" runat="server"></asp:Label>
                <br />

                <asp:Label ID="Label2" runat="server" Text="<u>P</u>assword" AccessKey="P" AssociatedControlID="TextBox1"></asp:Label>
                <asp:TextBox ID="TextBox1" runat="server" TextMode="Password"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>
                <asp:CompareValidator  ID="CompareValidator" runat="server" ControlToValidate="TextBox2" ControlToCompare="TextBox1" ErrorMessage="Password does not match!">
                </asp:CompareValidator>
                <br />

                <asp:Label ID="Label3" runat="server" Text="Re-Type Password" AssociatedControlID="TextBox2"></asp:Label>
                <asp:TextBox ID="TextBox2" runat="server" TextMode="Password"></asp:TextBox>
                <br />
               

                <asp:Label ID="Label4" runat="server" Text="Data Type check"  ></asp:Label>
                <asp:TextBox ID="TextBox3" runat="server" ></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TextBox3" Text="*"></asp:RequiredFieldValidator>
                <asp:CompareValidator  ID="CompareValidator1" runat="server" ControlToValidate="TextBox3" Operator="DataTypeCheck"  Type="Integer" ErrorMessage=" Give proper data type value">
                </asp:CompareValidator>
                <br />


                  <asp:Label ID="Label5" runat="server" Text="Date valuek"  ></asp:Label>
                <asp:TextBox ID="TextBox4" runat="server" ></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="TextBox4" Text="*"></asp:RequiredFieldValidator>
                <asp:CompareValidator  ID="CompareValidator2" runat="server" ControlToValidate="TextBox4" Operator=DataTypeCheck  Type="Date"  ErrorMessage=" Give proper date value">
                </asp:CompareValidator>
                <br />

                <asp:Button ID="Button1" runat="server" Text="Compare" OnClick="Button1_Click" />
            </div>
        </form>
    </body>
</html>


------------------------------------------------------------------------------------
code View
-------------

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label1.Text = "Form Submited and Password matched."
    End Sub

Required Field Validator Example


Design View
----------------------------------------------------------------------
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>


<body>

<h3><font face="Verdana">Simple RequiredField Validator Sample</font></h3>

<form id="Form1" runat="server">

    <table bgcolor="#eeeeee" cellpadding=10>
    <tr valign="top">
      <td colspan=3>
        <asp:Label ID="lblOutput" Text="Fill in the required fields below" ForeColor="red" Font-Names="Verdana" Font-Size="10" runat=server /><br>
      </td>
    </tr>

    <tr>
      <td colspan=3>
      <font face=Verdana size=2><b>Credit Card Information</b></font>
      </td>
    </tr>
    <tr>
      <td align=right>
        <font face=Verdana size=2>Card Type:</font>
      </td>
      <td>
        <ASP:RadioButtonList id=RadioButtonList1 RepeatLayout="Flow" runat=server>
            <asp:ListItem>MasterCard</asp:ListItem>
            <asp:ListItem>Visa</asp:ListItem>
        </ASP:RadioButtonList>
      </td>
      <td align=middle rowspan=1>
        <asp:RequiredFieldValidator id="RequiredFieldValidator1"
            ControlToValidate="RadioButtonList1"
             Display="Static"
             ErrorMessage="choose the card type"
            InitialValue="" Width="100%" runat=server ForeColor="Red">
            *
        </asp:RequiredFieldValidator>
      </td>
    </tr>
    <tr>
      <td align=right>
        <font face=Verdana size=2>Card Number:</font>
      </td>
      <td>
        <ASP:TextBox id=TextBox1 runat=server />
      </td>
      <td>
        <asp:RequiredFieldValidator id="RequiredFieldValidator2"
            ControlToValidate="TextBox1"
            Display="Dynamic"
              ErrorMessage="enter value to the cardnumber"
            Width="100%" runat=server ForeColor="Red">
           *
        </asp:RequiredFieldValidator>

      </td>
    </tr>
    <tr>
      <td align=right>
        <font face=Verdana size=2>Expiration Date:</font>
      </td>
      <td>
        <ASP:DropDownList id=DropDownList1 runat=server>
            <asp:ListItem></asp:ListItem>
            <asp:ListItem >06/00</asp:ListItem>
            <asp:ListItem >07/00</asp:ListItem>
            <asp:ListItem >08/00</asp:ListItem>
            <asp:ListItem >09/00</asp:ListItem>
            <asp:ListItem >10/00</asp:ListItem>
            <asp:ListItem >11/00</asp:ListItem>
            <asp:ListItem >01/01</asp:ListItem>
            <asp:ListItem >02/01</asp:ListItem>
            <asp:ListItem >03/01</asp:ListItem>
            <asp:ListItem >04/01</asp:ListItem>
            <asp:ListItem >05/01</asp:ListItem>
            <asp:ListItem >06/01</asp:ListItem>
            <asp:ListItem >07/01</asp:ListItem>
            <asp:ListItem >08/01</asp:ListItem>
            <asp:ListItem >09/01</asp:ListItem>
            <asp:ListItem >10/01</asp:ListItem>
            <asp:ListItem >11/01</asp:ListItem>
            <asp:ListItem >12/01</asp:ListItem>
        </ASP:DropDownList>
      </td>
      <td>
        <asp:RequiredFieldValidator id="RequiredFieldValidator3"
          ControlToValidate="DropDownList1"
          Display ="Static"  ErrorMessage="Select the expiration date"
          InitialValue="" Width="100%" runat=server ForeColor="Red">
          *
        </asp:RequiredFieldValidator>
      </td>
      <td>
    </tr>
 
    <tr>
      <td></td>
      <td>
        <ASP:Button id=Button1 text="Validate"  runat=server />
     

     
      </td>
      <td></td>
    </tr>
    <tr>
    <td>
 
    <asp:DropDownList id="ListFormat" AutoPostBack=true OnSelectedIndexChanged="ListFormat_SelectedIndexChanged" runat=server >
    <asp:ListItem>List</asp:ListItem>
    <asp:ListItem selected>Bulleted List</asp:ListItem>
    <asp:ListItem>Single Paragraph</asp:ListItem>
</asp:DropDownList>
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <asp:ValidationSummary ID="valSum" runat="server" DisplayMode="BulletList"
                HeaderText="You must enter a value in the following fields:"
                Font-Names="verdana"
                Font-Size="12"
                />
    </td>
    </tr>
    </table>

    <br />
    Dynamic : not take any space at run time when validataion succeeds<br />
    Static : Take space at runtime even the validation succeeds<br />
    InitialValue : doesn&#39;t consider as value specified at the control need to give
    another value apart from initial value</form>

</body>
</html>
-------------------------------------------------------------------------------------------

Code behind :
-----------------

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'Validate()
        End If
    End Sub

   

    Sub ListFormat_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)

        ' Change display mode of the validator summary when a new option
        ' is selected from the "ListFormat" dropdownlist

        valSum.DisplayMode = ListFormat.SelectedIndex
    End Sub



Thursday, August 6, 2015

Creating Advertisement using Adrotator control in ASP.NET

Step 1:  Add new item - XML file to the web page

Choose the xml file to write below coding for Advertisement
Copy the below code and paste it in the XML file and also include the relevent images which is specified name in your code ( Add existing item -> include appropriate images)


------------------------------------------
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
  <Ad>
    <ImageUrl>rose1.jpg</ImageUrl>
    <NavigateUrl>http://www.1800flowers.com</NavigateUrl>
    <AlternateText>
      Order flowers, roses, gifts and more
    </AlternateText>
    <Impressions>10</Impressions>
    <Keyword>flowers</Keyword>
    <Width>1000</Width>
    <Height>150</Height>
  </Ad>

  <Ad>
    <ImageUrl>rose2.jpg</ImageUrl>
    <NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
    <AlternateText>Order roses and flowers</AlternateText>
    <Impressions>10</Impressions>
    <Keyword>gifts</Keyword>
    <Width>1000</Width>
    <Height>150</Height>
  </Ad>

  <Ad>
    <ImageUrl>rose3.jpg</ImageUrl>
    <NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
    <AlternateText>Send flowers to Russia</AlternateText>
    <Impressions>10</Impressions>
    <Keyword>russia</Keyword>
    <Width>1000</Width>
    <Height>150</Height>
  </Ad>

  <Ad>
    <ImageUrl>rose4.jpg</ImageUrl>
    <NavigateUrl>http://www.edibleblooms.com</NavigateUrl>
    <AlternateText>Edible Blooms</AlternateText>
    <Impressions>10</Impressions>
    <Keyword>gifts</Keyword>
    <Width>1000</Width>
    <Height>150</Height>
  </Ad>
</Advertisements>
----------------------------------------------------------
These are all the description of  Standard XML tags for creating Advertisements in Webpage.
Element Description
Advertisements Encloses the advertisement file.
Ad Delineates separate ad.
ImageUrl The path of image that will be displayed.
NavigateUrl The link that will be followed when the user clicks the ad.
AlternateText The text that will be displayed instead of the picture if it cannot be displayed.
Keyword Keyword identifying a group of advertisements. This is used for filtering.
Impressions The number indicating how often an advertisement will appear.
Height Height of the image to be displayed.
Width Width of the image to be displayed.
-------------------------------------------------------------------------------------


Added images to the existing application:


Step 2:  In the design / Source view copy the below code or just drag and place the Adrotator control


        <asp:AdRotator ID="AdRotator2" runat="server" AdvertisementFile="~/ADXMLFile.xml" />

here the  AdvertisementFile attribute which specifies the XML file we have created to dentoe the various images with their corresponding attributes.


Step 3:
      
              Then run the page press "F5" . At the initial stage you will be see the singe image for the very first time. then  Refreshing the page you may able to see the random of images according to impression you have given to the particular image.


The above steps can be used to display random Advertisement can be shown when the page is Refreshed. If we want to show the Advertisement Randomly without refreshing the page means should use with Ajax enabled controls like Script manager , Update Panel etc.....

Just copy the below code in source view to see the difference:

  <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
         <asp:Timer ID="Timer1" Interval="1000" runat="server" >
                </asp:Timer>
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
             <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
        </Triggers>
            <ContentTemplate>

                <asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile="~/ADXMLFile.xml" />
              
            </ContentTemplate>
        </asp:UpdatePanel>







Saturday, August 1, 2015

HTML control Event in ASP.net Code behind and Client Script

this is for HTML control event at client side script function

just copy the below code in source page of ur asp.net application

<html xmlns="http://www.w3.org/1999/xhtml" >
    <script language="VB" runat="server">
       Sub FancyBtn_Click(Source As Object, E as EventArgs)
          Message.InnerHtml = "Your name is: " & Name.Value
       End Sub
    </script>

    <head runat="server">
    <title> Enter Name: </title>
</head>
<body>
          <form id="form1" method="post" runat="server">

            <h3> Enter Name: <input id="Name" type="text" size="40" runat="server" />
            </h3>

             <button onserverclick=" FancyBtn_Click" runat="server">
               <b><i> I'm a fancy HTML 4.0 button </i> </b>
             </button>


           <h1>
             <span id="Message" runat="server"></span>
           </h1>

          </form>
       </body>
 </html>




---------------------------------------------------------

this is for HTML control event at server side code behind function

just copy the below code in view code of ur asp.net application
   Sub FancyBtn_Click(Source As Object, E as EventArgs)
          Message.InnerHtml = "Your name is: " & Name.Value
       End Sub


but comment the  below code in htmlsource view
/*<script language="VB" runat="server">
       Sub FancyBtn_Click(Source As Object, E as EventArgs)
          Message.InnerHtml = "Your name is: " & Name.Value
       End Sub
    </script>*/

 

Thursday, July 23, 2015

Wednesday, July 8, 2015

ASP.NET HTML code

<body>
    <form id="form1" runat="server">
    <div>
    <%--<h2>Spectacular Mountain</h2>--%>
   <%-- <table width="100%" border="2"
            style=" background-image: url('pic_mountain.jpg'); border-bottom-color:  Aqua; height: 347px;">--%>

<table width="100%" border="2"
            style=" border-bottom-color:  Aqua; ">
    <tr >
    <td colspan="3" width="100%" style="background-color: Blue ">
  <marquee>  <asp:Label ID="Label1" runat="server" Text="WELCOME" ForeColor="DarkOrange" Font-Bold="true" Font-Size="X-Large"  ></asp:Label> </marquee>
     
    <img src="pic_mountain.jpg" width="100%"  height="50%"   alt="Mountain View"/>
    </td>
    </tr>

    <tr>
 
    <td  width="20%" style="border:none">
 
 
    <asp:HyperLink ID="HyperLink1" NavigateUrl="~/Home.aspx" runat="server"> HOME </asp:HyperLink>
    <br />
 
     <asp:HyperLink ID="HyperLink2" NavigateUrl="~/Home.aspx" runat="server"> HOME </asp:HyperLink>
     <br />
      <asp:HyperLink ID="HyperLink3" NavigateUrl="~/Home.aspx" runat="server"> HOME </asp:HyperLink>
      <br />
       <asp:HyperLink ID="HyperLink4" NavigateUrl="~/Home.aspx" runat="server"> HOME </asp:HyperLink>
       <br />
        <asp:HyperLink ID="HyperLink5" NavigateUrl="~/Home.aspx" runat="server"> HOME </asp:HyperLink>
        <br />
         <asp:HyperLink ID="HyperLink6" NavigateUrl="~/Home.aspx" runat="server"> HOME </asp:HyperLink>
         <br />
          <asp:HyperLink ID="HyperLink7" NavigateUrl="~/Home.aspx" runat="server"> HOME </asp:HyperLink>
          <br />
           <asp:HyperLink ID="HyperLink8" NavigateUrl="~/Home.aspx" runat="server"> HOME </asp:HyperLink>
           <br />
            <asp:HyperLink ID="HyperLink9" NavigateUrl="~/Home.aspx" runat="server"> HOME </asp:HyperLink>
            <br />
 
    </td>

    <td width="40%" style="border:none;" valign="top" align="justify">
    <h2 style="color:Olive "  align="center">
    LEARN TO FIX YOUR LOYALITY
    </h2>


     <p   style="background-color:Orange; font-size:larger; color:Blue  ">

Once there broke a war between the birds and the beasts. Many battles were fought one after the other. If vow the birds got the upper hand, the next time beasts were successful.

The bats played a very treacherous role in this war. They sided with whichever side got the better of the other. Thus they were changing their loyalty from side to side.

Neither side paid any attention to the bats till the war lasted. But when the war got over, the bats didn't know which side to go. First, they went to the birds. But the birds refused to own them as many birds had seen them fighting for the beasts.

Then, the bats went to the beasts. But there also they faced the same situation.

So, they were left all alone because of their disloyalty.
<br />
  <font style=" font-size:x-large; background-color:Orange;"> &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp;The End.. </font>
 
   <%--  <font style=" font-size:x-large; background-color:Orange;"> <center> The End..  </center> </font>--%>

 
 
</p>

    </td>
    <td width="40%" style="border:none">
 
     <h2 style="color:Olive "  align="center">
    UNITED WE STAND ;DIVIDED WE FALL
    </h2>
    <p   style="background-color:Olive; font-size:larger ">
 


Once upon a time three sons were engaged in merchantile business under the supervision of their father. They were very rich. Each son was proficient in his own department.

If one was good in sales, the other one was competent in purchases and similarly the third one in finance.

Unluckily, one day the father got bed ridden and the sons decided to divide the business under the fallacy that each of them were experts in their own way and can handle their individual business solely.

The father was glum and grumpy with their decision but was helpless and unfortunately the separation took place.

As a result three of them became each other's competitors. With the passage of time, they started having huge losses in their respective businesses. They tried all possible ways to succeed but the situation became worse.

Then they came to their father for a piece of advice. The father said "when you all were doing the business jointly, the business ran successfully. But it was not any one of you responsible for the success of the business rather traits of all three of you put together made the business successful".

The sons realized their mistake & got reunited. So we conclude that disunity always ruins.
The End..
 
    </p>
    </td>
    </tr>
    </table>



    </div>
    </form>
</body>




-----------------



Another Page


---------------

<body style="background-color:Green">
    <form id="form1"  runat="server">
    <div>
        <p style="font-size:xx-large; font-family:AngsanaUPC; color:Fuchsia; background-color:Olive">
       
      <marquee>    <% Response.Write("welcome to the Home page")%>    </p>    </marquee>
    </div>
    </form>
</body>

Tuesday, March 31, 2015

JAVA JDBC Code

//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   
public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query to create statment with
      // required arguments for RS example.
      System.out.println("Creating statement...");
      stmt = conn.createStatement(
                           ResultSet.TYPE_SCROLL_INSENSITIVE,
                           ResultSet.CONCUR_READ_ONLY);
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

      // Move cursor to the last row.
      System.out.println("Moving cursor to the last...");
      rs.last();
      
      //STEP 5: Extract data from result set
      System.out.println("Displaying record...");
      //Retrieve by column name
      int id  = rs.getInt("id");
      int age = rs.getInt("age");
      String first = rs.getString("first");
      String last = rs.getString("last");
  
      //Display values
      System.out.print("ID: " + id);
      System.out.print(", Age: " + age);
      System.out.print(", First: " + first);
      System.out.println(", Last: " + last);

      // Move cursor to the first row.
      System.out.println("Moving cursor to the first row...");
      rs.first();
      
      //STEP 6: Extract data from result set
      System.out.println("Displaying record...");
      //Retrieve by column name
      id  = rs.getInt("id");
      age = rs.getInt("age");
      first = rs.getString("first");
      last = rs.getString("last");
  
      //Display values
      System.out.print("ID: " + id);
      System.out.print(", Age: " + age);
      System.out.print(", First: " + first);
      System.out.println(", Last: " + last);
     // Move cursor to the first row.

      System.out.println("Moving cursor to the next row...");
      rs.next();
      
      //STEP 7: Extract data from result set
      System.out.println("Displaying record...");
      id  = rs.getInt("id");
      age = rs.getInt("age");
      first = rs.getString("first");
      last = rs.getString("last");
  
      //Display values
      System.out.print("ID: " + id);
      System.out.print(", Age: " + age);
      System.out.print(", First: " + first);
      System.out.println(", Last: " + last);

      //STEP 8: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end JDBCExample

Friday, March 13, 2015

JAVA JDBC

import java.sql.*;
import java.io.*;

class dataDB
{
DataInputStream in =new DataInputStream(System.in);
Connection con;
void  connect()
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:she","scott","tiger");
System.out.println("Connected");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void insert()throws IOException
{
Statement stmt;
try
{
stmt=con.createStatement();
System.out.println("How many records to insert?");
int n=Integer.parseInt(in.readLine());
for(int i=1;i<=n;i++)
{
System.out.println("Enter studid:");
int si=Integer.parseInt(in.readLine());
System.out.println("Enter stud name:");
String na=in.readLine();
System.out.println("Enter marks:");
int ma=Integer.parseInt(in.readLine());
String query="insert into studs values("+si+",'"+na+"',"+ma+")";
int rows=stmt.executeUpdate(query);
System.out.println("Rows Inserted");
con.commit();
}
}
catch(Exception e1)
{
System.out.println(e1+"Exception insertion");
}
}
void create()
{
Statement stmt;
try
{
stmt=con.createStatement();
String query="create table studs(studid number,name text,marks number)";
int rows=stmt.executeUpdate(query);
System.out.println("Table Created");
}
catch(SQLException e1)
{
System.out.println(e1.getMessage());

}
}

void update()throws IOException
{
Statement stmt;
try
{
stmt=con.createStatement();
System.out.println("Enter studid to update:");
int sid=Integer.parseInt(in.readLine());
System.out.println("Enter new marks:");
int ma=Integer.parseInt(in.readLine());
String query="update studs set marks="+ma+ " where studid="+sid;
int rows=stmt.executeUpdate(query);
System.out.println(rows+"Rows Updated");
con.commit();
}
catch(Exception e1)
{
System.out.println(e1.getMessage());
}
}

void delete()throws IOException
{
Statement stmt;
try
{
stmt=con.createStatement();
System.out.println("Enter studid:");
int si=Integer.parseInt(in.readLine());
String query="delete from studs where studid="+si;
int rows=stmt.executeUpdate(query);
System.out.println(rows+"Rows Deleted");
con.commit();
}
catch(Exception e1)
{
System.out.println(e1+"Exception Deletion");
}
}

void disp()throws IOException
{
Statement stmt;
try
{
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from studs");
System.out.println("Student Details");
System.out.println("Studid      Name    Marks");
while(rs.next())
{
System.out.print(rs.getInt(1)+"           ");
System.out.print(rs.getString(2)+"           ");
System.out.print(rs.getString(3)+"         \n ");
}
}
catch(Exception e1)
{
System.out.println(e1+"Exception insertion");
}
}

public static void main(String ar[])throws IOException
{
DataInputStream in =new DataInputStream(System.in);
dataDB d=new dataDB();
int c;
System.out.println("VARIOUS OPERATION ON DATABASE");
d.connect();
do
{
System.out.println("1.create");
System.out.println("2.insert");
System.out.println("3.delete");
System.out.println("4.modify");
System.out.println("5.display");
System.out.println(" enter ur choice:");
int ch=Integer.parseInt(in.readLine());
switch(ch)
{
case 1:
d.create();
break;
case 2:
d.insert();
break;
case 3:
d.delete();
break;
case 4:
d.update();
break;
case 5:
d.disp();
break;
}
System.out.println("Enter 1->Continue");
c=Integer.parseInt(in.readLine());
}while(c==1);
}
}

Friday, March 6, 2015

Applet Frame

// Create a child frame window from within an applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletFrame" width=400 height=600>
</applet>
*/
// Create a subclass of Frame.
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString("This is in frame window", 10, 40);
}
}
class MyWindowAdapter extends WindowAdapter {
SampleFrame sampleFrame;
public MyWindowAdapter(SampleFrame sampleFrame) {
this.sampleFrame = sampleFrame;
}
public void windowClosing(WindowEvent we) {
sampleFrame.setVisible(false);
}
}
// Create frame window.
public class AppletFrame extends Applet implements ActionListener  {

 Button okButton;
TextField nameField;

Frame f;
public void init() {

f = new SampleFrame("A Frame Window");


okButton = new Button("Action!");

 nameField = new TextField("Type here Something",35);


add(okButton);


okButton.addActionListener(this);



}
public void start() {

}
public void stop() {
f.setVisible(false);
}


 public void actionPerformed(ActionEvent evt)
         {
  // Here we will ask what component called this method
              if (evt.getSource() == okButton)
{


f.setSize(150, 150);
f.setVisible(true);


f.add(nameField);
nameField.setText("hello");
//nameField.setText("hello"));
}


}

public void paint(Graphics g) {
g.drawString("This is in applet window", 15, 30);
}

}