Monday, 1 December 2014

What is Synchronized method ?

Leave a Comment
The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements. The more complex of the two, synchronized statements, are described in the other post. This section is about synchronized methods.

What is Synchronized method in java,Synchronized method in java,method in java,in java,


To make a method synchronized, simply add the synchronized keyword to its declaration:
public class SynchronizedCounter {
    private int c = 0;
    public synchronized void increment() {
        c++;
    }
    public synchronized void decrement() {
        c--;
    }
    public synchronized int value() {
        return c;
    }
}
If count is an instance of SynchronizedCounter, then making these methods synchronized has two effects:


  • First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
  • Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.
Note: 
Constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

Warning:
When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain a List called instances containing every instance of class. You might be tempted to add the following line to your constructor:
instances.add(this);
But then other threads can use instances to access the object before construction of the object is complete.

Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.

Important Point:
(An important exception: final fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) .
Read More

Friday, 28 November 2014

Two free tools for all Android Developers

Leave a Comment
Hello friends today i am telling you two free tools for android developers by which you android application made easy .
First tool is Android Button Maker and other is Android Asset Studio.

Two free tools for all Android Developers,best free tools for android,android designing tools free



  • Android Buttton Maker

Android Button Maker is online tool to generate buttons code for Android Apps. Android API provide Drawable Resources where XML file defines geometric shape, including colors, border and gradients.

These button is generating based on shape drawable XML code which load faster compare to normal png buttons. You can customize button properties in setting panel and get source code.

View this Tools Site



  • Android Asset Studio

Creating different icon types in several densities, with the right gradient color, shadow, borders, selected/unselected state etc, can be quite time-consuming. This is a great tool for Android Developers that need to build the icons for their application within a few minutes.
The Android Asset Studio has several tools in it including

  1. Launcher icons
  2. Action bar and tab icons
  3. Notification icons
  4. Navigation drawer indicator
  5. Generic icons

It is best to use it in Chrome.

View this Tools Site

Read More

Friday, 17 October 2014

What is the Reason behind the naming of Great Project

Leave a Comment
Ever wondered about how the project , framework or product names are coined ? Why the particular name , what does it mean.Why name hibernate or hadoop or mule. Whenever i came across a new technology or framework , first i search the meaning of the name, sometimes, it gives a fairly good idea about what the product is about, thus giving you a better understanding about the technology, and sometimes it has some interesting and funny stories behind the naming. I have collected some famous projects and reasoning behind the names

Why name GIT :
According to WikiPedia
Linus Torvalds[The creator of git] has quipped about the name git, which is Irish slang for a child born out of wedlock, and British English slang for a stupid or unpleasant person. Torvalds said: "I'm an egotistical bastard, and I name all my projects after myself. First 'Linux', now 'git'."The man page describes git as "the stupid content tracker"


Why Name Android:
Meaning of Android is "(in science fiction) A robot with a human appearance. all the android versions[Jelly Bean,Ice Cream Sandwich,Honeycomb,Gingerbread,Froyo,Eclair,Donut] till date , are named after popular sweets.

Why Name Hibernate:
Its name seems logical because hibernate mean " Remain inactive or indoors for an extended period". Similarly the hibernate entities remains inactive for the period they are in database. There is no official reason about naming.

Why Name Spring :
According to Blog by Rod Johnson spring was coded with name "Interface21 framework" , but later changed to spring suggested by yann . The reason was one is association to nature and two it represents a fresh start after the “winter" of traditional J2EE.

Why Name Mule
Mule is a popular ESB provider.Here is the quote as to why it is named as mule
“After working on a couple of systems, I found that there was a lot of infrastructure work to be done. I regard this infrastructure work as “donkey work” as it needs doing for ev- ery project. I preferred Mule over Donkey and Ass just didn’t seem right ;-). A Mule is also commonly referred to as a carrier of load, moving it from one place to another. The load we specialize in moving is your enterprise information.” —Ross Mason, CTO & Co-Founder, Mule Inc.


Why Name Hadoop
Hadoop was created by Doug Cutting and Michael J. Cafarella.Doug, who was working at Yahoo at the time,[8] named it after his son's toy elephant.

Why name Camel
Listing few reason which are there on Apache camel site :
a Camel can travel for great distances without water; similarly a Camel does not require bucket loads of XML
a Camel looks really funny when its running, like most of the team
Don't get lost in a desert of XML config files, get Camel!
some members of the team used to love Camel cigarettes!


Why name Tomcat
Tomcat started off as a servlet reference implementation by James Duncan Davidson.He wanted to name the project after an animal. He came up with Tomcat since he reasoned the animal represented something that could fend for itself.Catalina is Tomcat's servlet container .Coyote is Tomcat's HTTP Connector component.Jasper is Tomcat's JSP Engine.

Why name Apache
The name 'Apache' was chosen from respect for the various Native American nations collectively referred to as Apache, well-known for their superior skills in warfare strategy and their inexhaustible endurance.The group of developers who released this new software soon started to call themselves the "Apache Group".

Apart from this , various java releases project names are based on mammels and birds while minor release names are based on insects[because they are bug fixes releases ].Java 5 release was named as Tiger , Java 6 as Mustang and java 7 as Dolphin .

Why Name AMAZON:
Amazon[need no introduction] was founded by Jeff Bezos. Bezos wanted a name for his company that began with "A" so that it would appear early in alphabetic order. He began looking through the dictionary and settled on "Amazon" because it was a place that was "exotic and different" and it was one of the biggest rivers in the world, as he hoped his company would be!

Why Name Geronimo :
Apache Geronimo is an open  server runtime that integrates the best open  projects to create Java/OSGi server runtime. Geronimo was an Apache leader who fought with US and mexico army.There is also a controversy that the U.S. operation to kill Osama bin Laden also used the code name "Geronimo".

Why Name Selenium :
The open  Selenium web testing tool was named as a jab at its ostensible commercial rival, Mercury QuickTest Pro (Mercury was later bought by HP). Selenium mineral supplements are used as an antidote to mercury poisoning, and so was the test tool meant as an antidote to QTP!

Why Name DJango:
Django is a high-level Python Web framework and named after the jazz guitarist Django Reinhardt.

Why Name Perl:
Programming language Perl [created by Larry Wall]was originally named "Pearl". Wall wanted to give the language a short name with positive connotations; he claims that he considered (and rejected) every three- and four-letter word in the dictionary. He also considered naming it after his wife Gloria. Wall discovered the existing PEARL programming language before Perl's official release and changed the spelling of the name.

Why Name Ruby:
Ruby was conceived on February 24, 1993 by Yukihiro Matsumoto who wished to create a new language that was more powerful than Perl, and more object-oriented than Python.The main factor in choosing the name "Ruby" was because it was the birthstone of one of his colleagues

Why Name Mozilla :
Mozilla was the mascot of the now disbanded Netscape Communications Corporation.The name "Mozilla" was already in use at Netscape as the codename for Netscape Navigator 1.0. The term came from a combination of "Mosaic killer" (as Netscape wanted to displace NCSA Mosaic as the world's number one web browser) and Godzilla. Apparently , Firefox , the flagship product of mozilla went through several name changes . Originally titled Phoenix , then changed to firebird and now firefox.

Why Name Yahoo!
The word "Yahoo" was invented by Jonathan Swift for the Travels.The name Yahoo! purportedly stands for "Yet Another Hierarchical Officious Oracle," but Jerry Yang and David Filo insist they selected the name because they considered themselves yahoos.The very first name of yahoo was "Akebono"[name of legendary Hawaiian sumo wrestlers].Yahoo name was already registered with someone else so a exclamation mark was put and made it yahoo!.

Why Name Windows:
The name Windows fits into that philosophy. At the time of its original release late in 1985, most operating systems were single-tasking, text-only, and ran from a command line--like DOS if you remember that. Graphic user interfaces (GUIs) were still new. The Mac, less than two years old at that time, was the only GUI-based system enjoying commercial success. The word windows simply described one of the most obvious differences between a GUI and a command-line interface.


Why Name Pramati
For those who don't know , pramati build application servers , just like JBOSS , APACHE etc. Pramati is a Sanskrit word which means "Exceptional Minds". I worked there as a java developer :) .

Why Name Scala
The name Scala is a blend of "scalable" and "language", signifying that it is designed to grow with the demands of its users. James Strachan, the creator of Groovy, described Scala as a possible successor to Java .

Why Name JBOSS AS:
JBoss Application Server is one of the most popular Java EE complaint server. The Term Jboss is short form of "JavaBeans Open  Software Application Server".
In 1999, Marc Fleury started a free software project named EJB-OSS (Enterprise Java Bean Open  Software) implementing the EJB API from J2EE (Java 2 Enterprise Edition). Sun Microsystems asked the project to stop using the EJB trademark within its name. EJB-OSS was then renamed to JBOSS, then JBoss later
Now the Jboss AS is renamed to Wildfly . All further releases of the JBOSS AS 7.1.1 Final will be named as wildfly .This name was chosen from a public voting among other names(BaseJump ,jBeret ,Petasos ,Jocron ) and the reason behind the name is "A wild fly is extremely agile, lightweight, untamed and truly free."


Why Name JIRA:
Jira is one of the most popular project and bug tracking tool developed by atlassian. The reason behind naming the project is :
We originally used Bugzilla for bug tracking and the developers in the office started calling it by the Japanese name for Godzilla, Gojira (the original black-and-white Japanese Godzilla films are also office favourites). As we developed our own bug tracker, and then it became an issue tracker, the name stuck, but theGo got dropped - hence JIRA!

Why Name Ubuntu:
Ubuntu is a operating system based on debian linux distribution.It is named after southern african philosophy ubuntu. According to their official web site :
Ubuntu is an ancient African word meaning 'humanity to others'. It also means 'I am what I am because of who we all are'. The Ubuntu operating system brings the spirit of Ubuntu to the world of computers.

Why Name Wikipedia:
Wikipedia was launched on January 15, 2001, by Jimmy Wales and Larry Sanger.Sanger coined the name Wikipedia, which is a combination of wiki and encyclopedia .The word wiki (a website which allows people to add, modify, or delete the content via a web browser usually using a simplified markup language or a rich-text editor) came from Ward Cunningham, the developer of the first wiki software, WikiWikiWeb.
WikiWikiWeb was the first wiki.Ward Cunningham started developing WikiWikiWeb in Portland, Oregon, in 1994, and installed it on the Internet domain c2.com on March 25, 1995. It was named by Cunningham, who remembered a Honolulu International Airport counter employee telling him to take the "Wiki Wiki Shuttle" bus that runs between the airport's terminals. According to Cunningham, "I chose wiki-wiki as an alliterative substitute for 'quick' and thereby avoided naming this stuff quick-web.

Why Name RedHat:
RedHat is leader in open  and provides large range of open  products to enterprise community. It has also acquired JBOSS.The reason behind the name RedHat is :
In an interview with Red Hat Magazine, co-founder Bob Young said that the red hat has long been a symbol of freedom, with revolutionaries in both America and France donning red caps during their uprisings. "There is a tradition in western history of red being the symbol of liberation and challenge of authority," he says in the taped interview. As for the name Red Hat specifically, fellow co-founder Marc Ewing also had an affinity for red hats and wore his grandfather's red lacrosse hat during his time at Carnegie Mellon.
The Fedora project created in 2003 when Red Hat Linux(Community Distribution ) was discontinued.A fedora is a kind of hat most commonly worn by men. 
Read More

Tuesday, 14 October 2014

How to Use MySQL Stored Procedure Parameters

Leave a Comment
In this tutorial, we will show you how to write MySQL stored procedures with parameters. We will also give you a couple of stored procedure examples to help you understand how to use different kinds of stored procedure parameters.

Almost stored procedures that you develop require parameters. The parameters make the stored procedure more flexible and useful.
In MySQL, a parameter has one of three modes IN, OUT or INOUT.
How to Use MySQL Stored Procedure Parameters,Use MySQL Stored Procedure Parameters,MySQL Stored Procedure Parameters,Stored Procedure Parameters,Procedure Parameters,MySQL stored procedure parameter examples,IN parameter example,OUT parameter example

  • IN – is the default mode. When you define an IN parameter in a stored procedure, the calling program has to pass an argument to the stored procedure. In addition, the value of an IN parameter is protected. It means that even the value of the IN parameter is changed inside the stored procedure, its original value is retained after the stored procedure ends. In other words, the stored procedure only works on the copy of the IN parameter.
  • OUT – the value of an OUT parameter can be changed inside the stored procedure and its new value is passed back to the calling program. Notice that the stored procedure cannot access the initial value of the OUT parameter when it starts.
  • INOUT – an INOUT parameter is the combination of IN parameter and OUT parameter. It means that the calling program may pass the argument, and the stored procedure can modify the INOUT parameter and pass the new value back to the calling program.
Example :

IN parameter example
The following example illustrates how to use the IN parameter in the GetOfficeByCountry stored procedure that selects offices located in a specified country.
DELIMITER //
CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(255))
 BEGIN
 SELECT * 
 FROM offices
 WHERE country = countryName;
 END //
DELIMITER ;
The countryName is the IN parameter of the stored procedure. Inside the stored procedure, we select all offices that locate in the country specified by the countryName parameter.

Suppose, you want to get all offices in the USA, you just need to pass a value (USA) to the stored procedure as follows:
CALL GetOfficeByCountry('USA')

OUT parameter example
The following stored procedure returns the number of orders by order status.
It has two parameters:

  1. orderStatus: IN parameter that is the order status which you want to count the orders.
  2. total: OUT parameter that stores the number of orders for a specific order status.

The following is the source code of the CountOrderByStatus stored procedure.
DELIMITER $$
CREATE PROCEDURE CountOrderByStatus(
 IN orderStatus VARCHAR(25),
 OUT total INT)
BEGIN
 SELECT count(orderNumber)
 INTO total
 FROM orders
 WHERE status = orderStatus;
END$$
DELIMITER ;
To get the number of shipped orders, we call the CountOrderByStatus stored procedure and pass the order status as Shipped, and also pass an argument (@total) to get the return value.
CALL CountOrderByStatus('Shipped',@total);
 
SELECT @total;

INOUT parameter example

The following example demonstrates how to use INOUT parameter in the stored procedure.
DELIMITER $$
CREATE PROCEDURE set_counter(INOUT count INT(4),IN inc INT(4))
BEGIN
 SET count = count + inc;
END$$
DELIMITER ;
How it works.

The set_counter stored procedure accepts one INOUT parameter ( count) and one IN parameter ( inc).
Inside the stored procedure, we increase the counter ( count) by the value of the inc parameter.
See how we call the set_counter stored procedure:
SET @counter = 1;
CALL set_counter(@counter,1); -- 2
CALL set_counter(@counter,1); -- 3
CALL set_counter(@counter,5); -- 8
SELECT @counter; -- 8
In this tutorial, we have shown you how to define parameters in stored procedures, and introduced you to different parameter modes including IN, OUT and INOUT.
Read More

Monday, 13 October 2014

How to make animated moving marker on Google map using javascript

Leave a Comment
Hello friends today i am telling you how you can be make animated marker on Google map using javascript.
How to make animated moving marker on Google map using javascript,make animated moving marker on Google map using javascript,animated moving marker on Google map using javascript,moving marker on Google map using javascript,marker on Google map using javascript,Google map using javascript,

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>GeekOnJava: Directions Complex</title>
  

<style>
html{height:100%;}
body{height:100%;margin:0px;font-family: Helvetica,Arial;}
</style>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type ="text/javascript" src="http://www.geocodezip.com/scripts/v3_epoly.js"></script>
<script type="text/javascript">
  
  var map;
  var directionDisplay;
  var directionsService;
  var stepDisplay;
 
  var position;
  var marker = [];
  var polyline = [];
  var poly2 = [];
  var poly = null;
  var startLocation = [];
  var endLocation = [];
  var timerHandle = [];
    
  
  var speed = 0.000005, wait = 1;
  var infowindow = null;
  
  var myPano;   
  var panoClient;
  var nextPanoId;
  
  var startLoc = new Array();
  startLoc[0] = 'rio claro, trinidad';
  startLoc[1] = 'preysal, trinidad';
  startLoc[2] = 'san fernando, trinidad';
  startLoc[3] = 'couva, trinidad';

  var endLoc = new Array();
  endLoc[0] = 'princes town, trinidad';
  endLoc[1] = 'tabaquite, trinidad';
  endLoc[2] = 'mayaro, trinidad';
  endLoc[3] = 'arima, trinidad';


  var Colors = ["#FF0000", "#00FF00", "#0000FF"];


function initialize() {  

  infowindow = new google.maps.InfoWindow(
    { 
      size: new google.maps.Size(150,50)
    });

    var myOptions = {
      zoom: 16,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    address = 'Trinidad and Tobago'
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
     map.fitBounds(results[0].geometry.viewport);

    }); 
  // setRoutes();
  } 


function createMarker(latlng, label, html) {
// alert("createMarker("+latlng+","+label+","+html+","+color+")");
    var contentString = '<b>'+label+'</b><br>'+html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: label,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });
        marker.myname = label;


    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString); 
        infowindow.open(map,marker);
        });
    return marker;
}  

function setRoutes(){   

    var directionsDisplay = new Array();

    for (var i=0; i< startLoc.length; i++){

    var rendererOptions = {
        map: map,
        suppressMarkers : true,
        preserveViewport: true
    }
    directionsService = new google.maps.DirectionsService();

    var travelMode = google.maps.DirectionsTravelMode.DRIVING;  

    var request = {
        origin: startLoc[i],
        destination: endLoc[i],
        travelMode: travelMode
    };  

        directionsService.route(request,makeRouteCallback(i,directionsDisplay[i]));

    }   


    function makeRouteCallback(routeNum,disp){
        if (polyline[routeNum] && (polyline[routeNum].getMap() != null)) {
         startAnimation(routeNum);
         return;
        }
        return function(response, status){
          
          if (status == google.maps.DirectionsStatus.OK){

            var bounds = new google.maps.LatLngBounds();
            var route = response.routes[0];
            startLocation[routeNum] = new Object();
            endLocation[routeNum] = new Object();


            polyline[routeNum] = new google.maps.Polyline({
            path: [],
            strokeColor: '#FFFF00',
            strokeWeight: 3
            });

            poly2[routeNum] = new google.maps.Polyline({
            path: [],
            strokeColor: '#FFFF00',
            strokeWeight: 3
            });     


            // For each route, display summary information.
            var path = response.routes[0].overview_path;
            var legs = response.routes[0].legs;


            disp = new google.maps.DirectionsRenderer(rendererOptions);     
            disp.setMap(map);
            disp.setDirections(response);


            //Markers               
            for (i=0;i<legs.length;i++) {
              if (i == 0) { 
                startLocation[routeNum].latlng = legs[i].start_location;
                startLocation[routeNum].address = legs[i].start_address;
                // marker = google.maps.Marker({map:map,position: startLocation.latlng});
                marker[routeNum] = createMarker(legs[i].start_location,"start",legs[i].start_address,"green");
              }
              endLocation[routeNum].latlng = legs[i].end_location;
              endLocation[routeNum].address = legs[i].end_address;
              var steps = legs[i].steps;

              for (j=0;j<steps.length;j++) {
                var nextSegment = steps[j].path;                
                var nextSegment = steps[j].path;

                for (k=0;k<nextSegment.length;k++) {
                    polyline[routeNum].getPath().push(nextSegment[k]);
                    //bounds.extend(nextSegment[k]);
                }

              }
            }

         }       

         polyline[routeNum].setMap(map);
         //map.fitBounds(bounds);
         startAnimation(routeNum);  

    } // else alert("Directions request failed: "+status);

  }

}

    var lastVertex = 1;
    var stepnum=0;
    var step = 50; // 5; // metres
    var tick = 100; // milliseconds
    var eol= [];
//----------------------------------------------------------------------                
 function updatePoly(i,d) {
 // Spawn a new polyline every 20 vertices, because updating a 100-vertex poly is too slow
    if (poly2[i].getPath().getLength() > 20) {
          poly2[i]=new google.maps.Polyline([polyline[i].getPath().getAt(lastVertex-1)]);
          // map.addOverlay(poly2)
        }

    if (polyline[i].GetIndexAtDistance(d) < lastVertex+2) {
        if (poly2[i].getPath().getLength()>1) {
            poly2[i].getPath().removeAt(poly2[i].getPath().getLength()-1)
        }
            poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),polyline[i].GetPointAtDistance(d));
    } else {
        poly2[i].getPath().insertAt(poly2[i].getPath().getLength(),endLocation[i].latlng);
    }
 }
//----------------------------------------------------------------------------

function animate(index,d) {
   if (d>eol[index]) {

      marker[index].setPosition(endLocation[index].latlng);
      return;
   }
    var p = polyline[index].GetPointAtDistance(d);

    //map.panTo(p);
    marker[index].setPosition(p);
    updatePoly(index,d);
    timerHandle[index] = setTimeout("animate("+index+","+(d+step)+")", tick);
}

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

function startAnimation(index) {
        if (timerHandle[index]) clearTimeout(timerHandle[index]);
        eol[index]=polyline[index].Distance();
        map.setCenter(polyline[index].getPath().getAt(0));

        poly2[index] = new google.maps.Polyline({path: [polyline[index].getPath().getAt(0)], strokeColor:"#FFFF00", strokeWeight:3});

        timerHandle[index] = setTimeout("animate("+index+",50)",2000);  // Allow time for the initial map display
}

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



</script>
</head>
<body onload="initialize()">

<div id="tools">

    <button onclick="setRoutes();">Start</button>

</div>

<div id="map_canvas" style="width:100%;height:100%;"></div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-162157-1";
urchinTracker();
</script>
</body>
</html>

Output of above code :
Read More

Friday, 3 October 2014

Work with MySQL Stored Procedure Variables

Leave a Comment
In this tutorial, you will learn about variables in stored procedure, how to declare, and use variables. In addition, you will learn about the scopes of variables.

If you're using xampp then check and for mysql workbench then check.

A variable is a named data object whose value can change during the stored procedure execution. We typically use the variables in stored procedures to hold the immediate results. These variables are local to the stored procedure.

How to Work with MySQL Stored Procedure Variables,Work with MySQL Stored Procedure Variables,MySQL Stored Procedure Variables,Stored Procedure Variables,How to declare variables in Mysql Store Procedure ,declare variables in Mysql Store Procedure ,variables in Mysql Store Procedure ,Variables scope


How to declare variables in Mysql Store Procedure ?
To declare a variable inside a stored procedure, you use the DECLARE statement as follows:
DECLARE variable_name datatype(size) DEFAULT default_value;
Let’s examine the statement above in more detail:
  • First, you specify the variable name after the  DECLARE keyword. The variable name must follow the naming rules of MySQL table column names.
  • Second, you specify the data type of the variable and its size. A variable can have any MySQL data types such as INT, VARCHAR, DATETIME, etc.
  • Third, when you declare a variable, its initial value is NULL. You can assign the variable a default value by using DEFAULT keyword.
For example, we can declare a variable named  total_sale with the data type INT and default value 0 as follows:
DECLARE total_sale INT DEFAULT 0
MySQL allows you to declare two or more variables that share the same data type using a single DECLARE statement as following:
DECLARE x, y INT DEFAULT 0
We declared two INT variables  x and  y , and set their default values to zero.
How to assign variable in Mysql Store Procedure ?
Once you declared a variable, you can start using it. To assign a variable another value, you use the SET statement, for example:
DECLARE total_count INT DEFAULT 0
SET total_count = 10;
The value of the total_count variable is 10 after the assignment.

Besides the SET statement, you can use SELECT INTO statement to assign the result of a query to a variable. Notice that the query must return a scalar value.
DECLARE total_products INT DEFAULT 0
 
SELECT COUNT(*) INTO total_products
FROM products
In the example above:

  • First, we declare a variable named total_products and initialize its value to 0.
  • Then, we used the SELECT INTO statement to assign the total_products variable the number of products that we selected from the products from the products table.
Variables scope

A variable has its own scope, which defines its life time. If you declare a variable inside a stored procedure, it will be out of scope when the END statement of stored procedure reached.

If you declare a variable inside BEGIN END block, it will be out of scope if the END is reached. You can declare two or more variables with the same name in different scopes because a variable is only effective in its own scope. However, declaring variables with the same name in different scopes is not good programming practice.

A variable that begins with the @ sign at the beginning is session variable. It is available and accessible until the session ends.

In this tutorial, we have shown you how to declare a variable inside stored procedures and discussed about the variable scopes.

Read More

Thursday, 2 October 2014

How to create Mysql Store Procedure using XAMPP

Leave a Comment
Hello friends today i am telling you How to create Mysql Store Procedure using XAMPP. First of all select your database here is classicmodels. 
After that click on SQL in XAMPP menu and paste the store procedure query.
If you want to know advantage/disadvantage of Store Procedure then check this.
DELIMITER //
 CREATE PROCEDURE GetAllProducts()
   BEGIN
   SELECT *  FROM products;
   END //
 DELIMITER ;
How to create Mysql Store Procedure using XAMPP,create Mysql Store Procedure using XAMPP,Mysql Store Procedure using XAMPP,Store Procedure using XAMPP,
If you want to details of above code for better understanding then check this post:
Develop the first MySQL stored procedure
Now click on Routines.And you'll see the created store procedure functions.


When you click on Execute then you can be see the all products details.
How to create Mysql Store Procedure using XAMPP,create Mysql Store Procedure using XAMPP,Mysql Store Procedure using XAMPP,Store Procedure using XAMPP,

Read More