Vamsi Pavan’s Place

When curiousity outbursts …..

Core Java: StringBuffer and StringBuilder

May 15th, 2008 · No Comments · Java

StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands as needed. Related classes: String, CharSequence.

StringBuilder was added in Java 5. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster.

No imports are necessary because these are both in the java.lang package.

Efficiency of StringBuffer compared to String

Because a StringBuffer object is mutable (it can be changed), there is no need to allocate a new object when modifications are desired. For example, consider a method which duplicates strings the requested number of times.

// Inefficient version using String.
public static String dupl(String s, int times) {
    String result = s;
    for (int i=1; i<times; i++) {
        result = result + s;
    }
    return result;
}

If called to duplicate a string 100 times, it would build 99 new String objects, 98 of which it would immediately throw away! Creating new objects is not efficient. A better solution is to use StringBuffer.

// More efficient version using StringBuffer.

public static String dupl(String s, int times) {
    StringBuffer result = new StringBuffer(s);
    for (int i=1; i<times; i++) {
        result.append(s);
    }
    return result.toString();
}

This creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer will automatically expand as needed. These expansions are costly however, so it would be better to create the StringBuffer the correct size from the start.

// Much more efficient version using StringBuffer.

public static String dupl(String s, int times) {
    StringBuffer result = new StringBuffer(s.length() * times);
    for (int i=0; i<times; i++) {
        result.append(s);
    }
    return result.toString();
}

Because this StringBuffer is created with the correct capacity, it will never have to expand. There is no constructor which allows both an initial capacity to be specifed and an initial string value. Therefore the loop has one extra iteration in it to give the correct number of repetitions.

Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • StumbleUpon
  • BlinkList
  • YahooMyWeb
  • NewsVine
  • blogtercimlap
  • Netvouz
  • Technorati
  • Slashdot
  • Print this article!

→ No CommentsTags:···

Core Java: marker interface

May 15th, 2008 · 2 Comments · Java

A marker or tagging interface is an interphase with no methods. It can be created by ANYBODY. the purpose of these interfaces is to create a special type of Object, in such a way that you are restricting the classes that can be cast to it without placing ANY restrictions on the exported methods that must be provided. It mostly indicates that a class should or should not be considered an acceptable class for a certain operation.

Some examples are:

Serializable: This is used to indicate that an object may be serialized for persistance purposes. It has no methods. The writeObject and readObject methods are actually not part of the interface, but rather part of the serialization process, and help determine how to serialize an object. hence, when using a design tool (like jBuilder), when you implement serializable, it automatically creates writeObject and readObject — But they are not necessary.

Cloneable: Every Object has a method clone(). But in order to call that method, a class must be marked as Cloneable. Thus, it is just another marking interface.

EventListener: EventListener is a tagging interface that is an important part of introspection in Java Beans. It is possible to use the Delegation Event design for events without implementing EventListener, but in order for the Java beans introspector to recognize the EventListener, it must be tagged by implementing java.util.EventListener.

And the list goes on…

Here’s an example where you could create youre own tagging interface:

let’s say you were modeling a department store. You have objects that represent all of the merchendise you can sell. Now, you have an initiative in the store that you will sell at least 70% American Made merchendise. Then you could create the interface

public interface AmericanMade {} 

and implement that on every object you sell that is made in America. Now, a customer come and wants to purchase only American Made products, so you show him a revised catalogue, like this:

for (Product product : allProducts) {  if (product instanceof AmericanMade) {    newList.add(product);  }} 

See, the whole point is that it creates a new type of merchendise, the AmericanMade, that can be distinguished from others, whether the product is Toilet Paper, T-Shirts, Motor Oil, or Golf Clubs. It does not define any properties or methods, though, because there is likely no difference between an american made golf club and an English golf club, except that buying one helps support the American economy, and the other hleps support the English economy.

Collected from Sun Java forums.

Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • StumbleUpon
  • BlinkList
  • YahooMyWeb
  • NewsVine
  • blogtercimlap
  • Netvouz
  • Technorati
  • Slashdot
  • Print this article!

→ 2 CommentsTags:···

Building DOM tree by reading an xml file in Java

December 19th, 2007 · No Comments · Java, Source Code

import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;

public class BasicDom {
public static void main(String[] args) {
Document doc = parseXmlFile(”infilename.xml”, false);
}

// Parses an XML file and returns a DOM document.
// If validating is true, the contents is validated against the DTD
// specified in the file.
public static Document parseXmlFile(String filename, boolean validating) {
try {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validating);

// Create the builder and parse the file
Document doc = factory.newDocumentBuilder().parse(new File(filename));
return doc;
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}
return null;
}
}

This is the common code used to parse XML files in Java. Often we see calling this method from other part of code as

Document doc = parseXmlFile(”infilename.xml”, false);

So, this become commonly used scripts in XML programming with Java.

Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • StumbleUpon
  • BlinkList
  • YahooMyWeb
  • NewsVine
  • blogtercimlap
  • Netvouz
  • Technorati
  • Slashdot
  • Print this article!

→ No CommentsTags:

MySQL error 1067 (42000): Invalid default value for ‘ban_id’

December 13th, 2007 · No Comments · Uncategorized

#
# Table structure for table ‘phpbb_banlist’
#
CREATE TABLE phpbb_banlist (
ban_id mediumint(8) unsigned DEFAULT ‘0′ NOT NULL auto_increment,
ban_userid mediumint(8) DEFAULT ‘0′ NOT NULL,
ban_ip varchar(8) DEFAULT ” NOT NULL,
ban_email varchar(255),
PRIMARY KEY (ban_id),
KEY ban_ip_user_id (ban_ip,ban_userid)
);

when you run the above code for creating new table, if you get (unexpectedly) the error:

ERROR 1067 (42000) at line 35: Invalid default value for ‘ban_id’

The reason would be the version problem of MySql Database (may be starting 5.x versions). It seems from 5.x version onwards, there is change in constraints part. You can’t set a DEFAULT value to an AUTO INCREMENT field.

For those, who are facing this problem, they can change the entire sql script just using this tip in Vim Editor.

s/\(.*\)DEFAULT ‘0′\(.*\)auto_increment/\1\2auto_increment/

It simply remove default values when ever auto_increment is set.

Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • StumbleUpon
  • BlinkList
  • YahooMyWeb
  • NewsVine
  • blogtercimlap
  • Netvouz
  • Technorati
  • Slashdot
  • Print this article!

→ No CommentsTags:

Hi Bloggy …. after long time ….

October 25th, 2007 · No Comments · Gen

It’s been a while updating my blog, I know. Of course, ups and downs are common in any life cycle whether it is human beings :) or a software development or a blog too. Ya, I know that’s too much of philosophical for nothing. Yes yes, now i understand the cost of shifting one company to another is it’s complete notice period. How hectic man! really, if you join cheap companies they always like to show hell to the employees who are in notice period. How sadistic activities …. sure, one day these bosses also get bosses of same nature and hope will show him same hell to stupid bossss ….! Aaaaa…. stop it, it’s over already, why to recollect past 2 months again. Let’s live for tomorrow …..

Any way, just want to say hi to all after long time and want to run this blog regularly again after long time. Hope everyone doing gr8 …. C ya.

Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • StumbleUpon
  • BlinkList
  • YahooMyWeb
  • NewsVine
  • blogtercimlap
  • Netvouz
  • Technorati
  • Slashdot
  • Print this article!

→ No CommentsTags:

Cross Browser Compatability - Web Resources

July 27th, 2007 · No Comments · Java Script

  1. http://www.zvon.org/xxl/xhtmlReference/Output/comparison.html compares  Strict and Transitional XHTML
  2. http://www.w3schools.com/ is a great web site for learning different web technologies
  3. http://www.quirksmode.org/dom/compatibility.html covers W3C DOM compatibility among different browsers and platforms
  4. http://www.w3schools.com/browsers/browsers_stats.asp provides up to date browser usage statistics
  5. http://nexgenmedia.net/evang/iemozguide/ provides migration guide from Internet Explorer to Mozilla
  6. http://www.w3.org/QA/Tools/#validators provides links for W3C (X)HTML/CSS validators.
Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • StumbleUpon
  • BlinkList
  • YahooMyWeb
  • NewsVine
  • blogtercimlap
  • Netvouz
  • Technorati
  • Slashdot
  • Print this article!

→ No CommentsTags:

Oracle Specific SQL Concepts - Part 1

July 24th, 2007 · No Comments · Pl/SQL

Some of the new concepts introduced as a part of Oracle new releases are:

Analytical Functions

In addition to the normal aggregate function like Max() etc. Oracle came up with some more commonly useful analytical functions, which can be implemented by PL/SQL logic. Mainly 5 commonly used functions are there:

  • rank() :– In a select statement after selecting certain data using over() function, you can apply this function to get the normal rank as separate column. It won’t take care of multiple rows with same ranks, simply returns rank on the basis.

Example: Consider the table Student<name, sub, marks, joining_date>.

Select name, marks, rank() over() (order by marks desc) st_rank

from Student

where st_rank = 2;

This generates the output as <name, marks, st_rank> with 1…last number. In case of repetition of ranks, next rank won’t be effected. So its like 1,2,2,3,4,4,4,5,….etc.

  • dense_rank() :– same as above rank() function, except that in case of repetition of the ranks the next coming ranks would be effected. For example, the series looks like 1,2,2,4,5,5,5,8,…etc. Syntax is same as above except to replace rank() by dense_rank().
  • LAG :– This will return the previous row of current selection. In case of selecting the consolation prizes generally, this would be the best to use.

Example: Consider same above Student table.

Select LAG( joining_date, 1 /*range operator to consider the previous record*/ )

over() (order by marks desc) from Student

where marks = 100.

This will return the student who joined immediately next to the student who got the marks 100.

  • LEAD :– Just to oppose of LAG. LAG is previous record where as LEAD is next record, that’s the only change. No change in the syntax except replacing LAG with LEAD.
  • over() :– This is an intermediate function provided by Oracle to support other functions like rank(), dense_rank(), and LAG etc. For syntax and usage you can refer to above examples in detail.
  • ROW_NUMBER :– This is very commonly used function to specify the row number of interest. Our of the entire selection, you can specify the row using this function. Using this, you can even implement the above functions like rank() and dense_rank() etc.

Partition By

This is just a replacement of group by in our general SQL. It’s functionality is same as group by, you can say this syntactically replacement given by Oracle. In addition to those normal grouping functionalities, it has extra features like handling segregation of memory etc.

In other words, suppose you need some 100 MB of memory for your database schema tables. But you have 100 MB memory but not continuous, then it’s not possible in normal case. In this type of cases, you can use partition by to allocate the required memory in different memory chunks available on the basis of some given column criteria. Generally, these things are very common to DBA not for Developer.

There are two types of partitions you can create. They are:

  • Using range :– While using partition by, you can mention the range of the values of the given column, on which the partitioning is going to happen.

Example: The SQL statement would be like this.

create <table_name> ( …. )

partition by (<some_column_name>)

(partition p1 value 10 and 50)           /* partition with name p1 has the values of given column between 10 and 50*/(partition p2 value 50 and 100)         /* similarly partition with name p2 has the range of value between 50 and 100*/

syntax presented here is not very sure. It has other functionalities like mentioning the memory size of the chunk/partition too. Need to explore for more syntaxes.

  • Using hash :– Similarly, instead of the range, Oracle provided internal function hash(). Using this, we need to mention the specific column on which this hash function need to create hash code, which is used as the criteria to store the table date in different memory chunks.

Example: The SQL statement would be.

create <table_name> ( …. )

partition by hash(<some_column_name>)   

/* Internally, hash function generates hash code for each record and based on that code, it would decide the memory chunk/partition to which it can be stored into.*/

This section on partition by need to be explored more to update this article.

 

Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • StumbleUpon
  • BlinkList
  • YahooMyWeb
  • NewsVine
  • blogtercimlap
  • Netvouz
  • Technorati
  • Slashdot
  • Print this article!

→ No CommentsTags:

I DNT HATE MOZILLA BUT USE IE OR ELSE…

July 20th, 2007 · No Comments · Windows

Recently I came across a new worm(virus) in my friend’s system. When I started firefox, I got a message I DNT HATE MOZILLA BUT USE IE OR ELSE… as pop up window with USE INTERNET EXPLORER U DOPE as window title. At first, I thought this is fun and surprised to see that there are people against to mozilla, after a while felt like crack this shit. Not only this, this guy also against to Orkut it seems, when ever I open orkut.com i get another pop up window with the message Orkut is banned you fool, The administrators didnt write this program guess who did?? MUHAHAHA!! and title as ORKUT IS BANNED. It seems this is a spyware attached to one of the free software downloads which is the routine habit of my roomie.

Any ways, I finally able to remove this guy out of my friend’s system. Just follow the below steps for windows users. I don’t think this would exist for Linux or other OS any way.

1. open your task manager by right click on toolbar and selecting the Task Manager.

2. find all the SVCHOST.exe processes with username as your login name.

3. select those processes, press Del key to kill those. When you get another pop up window message with Yes or No, select yes.

4. Now, go to start –> Run open the path C:\heap41a and delete all the files. This is a hidden folder and not visible by default.

5. Now go to Start –> Run and type Regedit.

6. Go to the menu Edit –> Find. Type “heap41a” here and press enter.

7. You will get something like this “[winlogon] C:\heap41a\svchost.exe C:\heap(some number)\std.txt”.

8. Select that and Press DEL. It will ask “Are you sure you wanna delete this value”, click Yes.

9. Now close the registry editor. That’s it, you did it.

Finally, though this type of worms are not new, but specific to firefox or mozilla is some wards weired. I heard my friend saying that some of anti-virus companies survive by release viruses themselves. The same way, I donno some of IE fans (if exists :)) may indulge these kind of things.

Any how, this head ache is out now. Letz go with our busy way….

    Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
    • bodytext
    • Sphinn
    • del.icio.us
    • Facebook
    • Mixx
    • Google
    • Live
    • StumbleUpon
    • BlinkList
    • YahooMyWeb
    • NewsVine
    • blogtercimlap
    • Netvouz
    • Technorati
    • Slashdot
    • Print this article!

    → No CommentsTags:

    Introduction to PHP’s PEAR classes : Comparing normal Database connections with PEAR classes.

    July 14th, 2007 · No Comments · PHP, Programming

    PHP Database Abstraction:

    Abstraction is a technique which simplifies something complex. It does this by removing non-essential parts of the object, allowing us to concentrate on the important parts.

    PEAR’s DB classes are one such database abstraction layer, and in this article we’ll take a look at some traditional database access methods and then compare them with the method employed by PEAR.

     

    Traditional Database Access

    Let’s quickly run through how you would connect to a database and run through the records using PHP’s native functions. We’ll start with MySQL since that seems to be one of the more popular databases. Note to Postgresql users - I said _more_ popular, not _most_ popular, so you can hold back on that hate mail for the moment :) [ *cough* -tim ]

    Here’s an SQL dump for the database that I am using. It’s MySQL and the database is called phptst. It consists of a single table called demo which has 3 fields.

    # MySQL dump 8.11
    #
    # Host: localhost	Database: phptst
    #--------------------------------------------------------
    # Server version	3.23.28-gamma
    
    #
    # Table structure for table 'demo'
    #
    
    CREATE TABLE demo (
      demo_id mediumint(9) NOT NULL auto_increment,
      demo_stamp bigint(20),
      demo_text varchar(50),
      PRIMARY KEY (demo_id)
    );
    
    #
    # Dumping data for table 'demo'
    #
    
    INSERT INTO demo VALUES (1,978872113,'Record number 1');
    INSERT INTO demo VALUES (2,978872652,'Record number 2');
    INSERT INTO demo VALUES (3,978872652,'Record number 3');
    INSERT INTO demo VALUES (4,978872652,'Record number 4');
    INSERT INTO demo VALUES (5,978872652,'Record number 5');

    Right, on to the code:


    <?php
    include( ‘dbinfo.php’ );
    $conn = mysql_connect( $dbhost, $dbuser, $dbpass );
    mysql_select_db($dbname);
    $sql = ‘SELECT * FROM demo’;
    $demoResult = mysql_query( $sql );
    while (
    $demoRow = mysql_fetch_row( $demoResult ) ) {
    echo
    $demoRow[2] . ‘<br>’;
    }
    mysql_close ($conn);

    ?>

     

    The first thing that I like to do is move all of my connection information out of the main script and into a small include file. This way when I change the password for the database I don’t have to go and edit every script that connects to that database. My dbinfo.php looks something like this:


    <?php
    $dbhost = ‘localhost’;
    $dbuser = ‘theuser’;
    $dbpass = ‘thepassword’;
    $dbname = ‘phptst’;

    ?>

     

    The line $conn = mysql_connect( $dbhost, $dbuser, $dbpass ); now uses the variables I set in dbinfo.php rather than having the info hard coded. OK. $conn is now a link identifier to my database connection. mysql_select_db($dbname); tells PHP which MySQL database I want to use.

     

    I set up my query with $sql = 'SELECT * FROM demo'; and then run the query on my database with $demoResult = mysql_query( $sql );. $demoResult is now an idetifier to the result set that my query just returned. We then use a while statement to loop through the result set:

     

    while ( $demoRow = mysql_fetch_row( $demoResult ) ) {

     

    each iteration populating the array $demoRow with next row of information from our result set. When we’re done we can close our connection to the database with a call to mysql_close().

    Here’s the output from that script:

     

    Record number 1
    Record number 2
    Record number 3
    Record number 4
    Record number 5

    If that quick and dirty run through mysql was too horrible to bear, there’s an intro article to PHP and MySQL on webmonkey.

     

    Doing it the PEAR way

    Out with the old, and in with the new - how the hell do we do that with PEAR ? Here’s our MySQL example above, rewritten using PEAR DB.


    <?php
    include(‘dbinfo.php’);
    require_once(
    ‘DB.php’ );
    $db = DB::connect( “mysql://$dbuser:$dbpass@$dbhost/$dbname” );
    $sql = ‘SELECT * FROM demo’;
    $demoResult = $db->query($sql);
    while (
    $demoRow = $demoResult->fetchRow()) {
    echo
    $demoRow[2] . ‘<br>’;
    }
    $db->disconnect();

    ?>

     

    OK, compare that to what we saw with MySQL. The process is pretty much the same (connect, query, loop through result, disconnect), but the way that we do each step has changed. Let’s go through it line by line and I’ll explain what’s going on.

     

    Our first line is as it was in our original script. I’m including my dbinfo.php so that I don’t have to hard code my database usernames and passwords. The next line require_once( "DB.php" ); is require’ing the file DB.php. The _once part makes sure that requires of files that contain duplicate variable or function declarations do not break your script.

     

    The file DB.php can be found in the /pear subdirectory of the PHP4 distribution. If the installation process didn’t do it, make sure that the directory that contains the PEAR files is included in your include_path in the php.ini.

    Inside DB.php a class of type DB is defined. One of the functions of the DB class is the connect() function, and this is what we are using here:


    <?php
    $db = DB::connect( “mysql://$dbuser:$dbpass@$dbhost/$dbname” );

    ?>

     

    The connect() function creates a new database object and connects to the database as specified in the string that you pass it. The string takes the format of:

     

    phptype://username:password@protocol+hostspec/database

    phptype is the type of database that you wish to connect to. Valid types are ibase, msql, mssql, mysql, oci8, odbc, pgsql and sybase.

    username, password and hostspec are self explanatory. protocol is the protocol to connect on (eg tcp) and database is the database that you want to use. The only thing in that string that is required is the phptype. Everything else is optional, but in most cases you are going to want to specify a username, password and database.

     

    If I wasn’t using the dbinfo.php include file the string I passed the connect function would look something like:
    "mysql://theuser:thepassword@localhost/phptst"

     

    Assuming that the connect() function succeeded, $db is now an object that not only contains methods for accessing your database but also contains all sorts of information about the conection you have just created.

     

    What is important for this example though, is that the object has a function called query() that will execute an SQL statement on the database. It returns a result object with it’s own properties and methods that we can use to get at the data.

    $demoResult = $db->query($sql);

     

    says “in the object $db is a function called query(). Run it with the argument $sql and stick the results you get back from it in

    $demoResult“.

     

    One of the functions in $demoResult is fetchRow(). fetchRow() will return a row of data as an array, much like mysql_fetch_row() will.

    while ($demoRow = $demoResult->fetchRow()) {

    fetchRow() is returning an array indexed numerically. What if you wanted to get an associative array back like you can with mysql_fetch_assoc() ? The fetchRow() function has an optional argument that specifies the type of array that will be returned by the function. If no argument is specified then DB_FETCHMODE_DEFAULT is assumed. It then returns whatever the default has been set to. If you wanted to explicitly specify each one, then you would use DB_FETCHMODE_ORDERED for an array index numerically, or DB_FETCHMODE_ASSOC for an array index by field name (associative). DB_FETCHMODE_DEFAULT, DB_FETCHMODE_ORDERED and DB_FETCHMODE_ASSOC are all constants that are defined in DB.php.

    So if we wanted to use an associative array, we would rewrite our code as follows:


    <?php
    while ($demoRow = $demoResult->fetchRow(DB_FETCHMODE_ASSOC)) {
    echo
    $demoRow[‘demo_text’] . ‘<br>’;
    }

    ?>

     

    Once we have finished with our connection to the database we can disconnect with $db->disconnect();.

    Let’s take another look at those two scripts side by side:

     

    Native PHP Functions PEAR

    <?php
    include( ‘dbinfo.php’ );
    // no need to include PEAR
    $conn = mysql_connect( $dbhost, $dbuser, $dbpass );
    mysql_select_db($dbname);
    $sql = ‘SELECT * FROM demo’;
    $demoResult = mysql_query( $sql );
    while (
    $demoRow = mysql_fetch_row( $demoResult ) ) {
    echo
    $demoRow[2] . ‘<br>’;
    }
    mysql_close ($conn);

    ?>


    <?php
    include(‘dbinfo.php’);
    require_once(
    ‘DB.php’ );
    $db = DB::connect( “mysql://$dbuser:$dbpass@$dbhost/$dbname” );
    // no need to select DB
    $sql = ‘SELECT * FROM demo’;
    $demoResult = $db->query($sql);
    while (
    $demoRow = $demoResult->fetchRow()) {
    echo
    $demoRow[2] . ‘<br>’;
    }
    $db->disconnect();

    ?>

     

    Great. So we’ve found another way of grabbing stuff data from my MySQL database. You may ask what the point is. Why not just do it the normal way ? Indulge me here for a moment.

    Suppose you decided to migrate to PostgreSQL.

    \connect - yourusernamehere
    CREATE TABLE "demo" (
    	"demo_id" int8 DEFAULT nextval('serial'::text) NOT NULL,
    	"demo_stamp" int8,
    	"demo_text" character varying(50),
    	PRIMARY KEY ("demo_id")
    );
    COPY "demo" FROM stdin;
    1	978872113	Record number 1
    2	978872652	Record number 2
    3	978872652	Record number 3
    4	978872652	Record number 4
    5	978872652	Record number 5
    \.

     

    There’s the same database dump but from PostegreSQL. Now if you had used native PHP database functions in your code you would first have to work out how the pgsql functions worked, and then you’d need to go play search and replace through all of your code.

    Course if you had used PEAR, you would go and change the line

     

    $db = DB::connect( “mysql://$dbuser:$dbpass@$dbhost/$dbname” );

     

    to

     

    $db = DB::connect( “pgsql://$dbuser:$dbpass@$dbhost/$dbname” );

     

    I did, reran the script and this is what I got:

    Record number 1
    Record number 2
    Record number 3
    Record number 4
    Record number 5

     

    Fairly nifty.

     

    What about error checking ?

     

    Say we ran the MySQL script again, and made a bit of a typo in the SQL statement - $sql = "SELECT * FROM demo2";

     

    Warning: Supplied argument is not a valid MySQL result resource in c:\temp\allan\db\mysql.php on line 7

     

    Messy. So we could add some error checking to the line that does the query:

     

    $demoResult = mysql_query( $sql ) or die( $sql );

     

    which now will output

     

    SELECT * FROM demo2

     

    Which means we have an error and we can go and debug it. Course if you’ve got a couple of inner joins happening you may not easily be able to work it out. And if I made a typo in one of the field names I was selecting:

     

    $sql = “SELECT bogus_field FROM demo”;

     

    I would get the same error message.

     

    MySQL has a useful function called mysql_error() which will return the last error that was generated, so changing the line:

     

    $demoResult = mysql_query( $sql ) or die( $sql );

     

    to

     

    $demoResult = mysql_query( $sql ) or die( mysql_error() );

     

    will now result in

     

    Table ‘phptst.demo2′ doesn’t exist

     

    in the first case and

     

    Unknown column ‘bogus_field’ in ‘field list’

     

    in the second.

     

    So what does PEAR have to offer in the way of error reporting ?

    The function DB::isError() will check to see whether the result that has been returned to you is an error or not. If it is an error you can use DB::errorMessage() to return a text description of the error that was generated. You need to pass DB::errorMessage() the return value from your function as an argument.

    Rewriting the PEAR code to use the error checking:


    <?php
    if ( DB::isError( $demoResult = $db->query( $sql ) ) ) {
    echo
    DB::errorMessage($demoResult);
    } else {
    while (
    $demoRow = $demoResult->fetchRow()) {
    echo
    $demoRow[2] . ‘<br>’;
    }
    }

    ?>

     

    Conclusion

    We’ve seen that PEAR is functional as a database abstraction layer, but is it a good database abstraction layer ?

    Let’s take a look at some properties of a good abstraction and see how PEAR fares:

    properly named
    The first thing you encounter in an abstracted object is it’s name, and you know what they say about first impressions.
    makes sense
    The properties and methods that make up the object should be appropriate for that object.
    minimal
    Introducing extraneous properties and methods only serve to complicate the object and your use thereof.
    complete
    The object must contain those properties and methods that are required to use the object for the purpose for which it was designed. A database object that lacks some fundamental database functionality is useless.

    All code that is submitted to PEAR adheres to the coding standards that have been agreed on by the core programmers in the group. Often, a lot of discussion surrounds the naming and contents of classes that are submitted to PEAR, so peer review takes care of points one and two.

     

    Even though the PEAR DB code is not without it’s bugs, development is ongoing. Hopefully this article has given you an idea of what is possible and a taste of things to come.

    Tags: ,

    Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
    • bodytext
    • Sphinn
    • del.icio.us
    • Facebook
    • Mixx
    • Google
    • Live
    • StumbleUpon
    • BlinkList
    • YahooMyWeb
    • NewsVine
    • blogtercimlap
    • Netvouz
    • Technorati
    • Slashdot
    • Print this article!

    → No CommentsTags:···

    Difference between String str=”abc” and str=new String(”abc”)?

    May 25th, 2007 · 6 Comments · Java, Placements

    1) using new operator:- String st=new String(”abc”);

    2) Without using new operator:- String st=”abc”;

    Once string object is created with or without new operator contents of string object cannot be modified. But we can modify String reference variable. when you are trying to modify string objects ie.. concatinating,repalcing etc.. a new string object will be created every time.

    Creating new object every time consumes more memory. To solve this problem sun introduce String Constant Pool mechanism.When you creating string object with new operator a new string will be created every time. It does not use string constant pool.When we are creating string object without new operator following things happened.

    a) JVM will check whether the string constant is available in the pool or not.

    b) If it is available in the pool same object referece will be assigned to new reference variable.

    c) If string constant is not available in the pool a new constant will be created and will be assigned to new reference variable and also placed this new constant in pool.

    Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
    • bodytext
    • Sphinn
    • del.icio.us
    • Facebook
    • Mixx
    • Google
    • Live
    • StumbleUpon
    • BlinkList
    • YahooMyWeb
    • NewsVine
    • blogtercimlap
    • Netvouz
    • Technorati
    • Slashdot
    • Print this article!

    → 6 CommentsTags: