Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Wednesday, December 19, 2012

Database: Oracle SQLPLUS command has vague behavior with comments.

In every project I am architecting, one of the main parts of architecture is the database architecture. Database architecture consists of developing ERD, meta-data document and finally the database script.

Database script is the organized and final set of files that allow DB administration, Testing team and Developers(runs script locally on their machines) to generate final database.

DB Scripts consist of a set of files. Each file contains related database types as separate .sql file. For example; tables has a file, triggers, types, packages, user and table space, views, and lookups ….. etc all of them has separate file.

The separation makes the final script maintainable.

Finally develop an OS (Windows, Mac, UNIX and Linux) specific script file to call all of the above described files in certain order the build final database from SQLPLUS.

One of interesting vague behavior I found while running the script is something like this:





This error "ERROR at line 1: ORA-00911: invalid character" prevents anything from being created, inserted, or compiled successfully.

To not fall in error like this again, which is inserting anything after the semicolon, don't code with the following code forms in the script (It will work from JDeveloper or SQL Developer):
  1. DDL OR DML STATEMENTS ; -- any comment.
  2. DDL OR DML STATEMENTS ; REM any comment.
  3. DDL OR DML STATEMENTS ; /*any comment.*/
The Solution is to put any comments before the semicolon as the following:
Bad example:
----------------


Good example:
------------------

Wednesday, April 11, 2012

JPA: Dynamic search builder, the power of annotation, reflection and generics.

JPA (Java persistence API) is a powerful tool for domain objects mapping, and object oriented view perspective of database.

Always I used to use JPA in my projects, but JPA2 introduces extra feature that facilitate the generic way of persisting, merging, deleting and searching. Also introduces dynamic criteria API, which I was looking for.

But with time I have to change the dynamic query or do it myself or else to create new dynamic one which the panic way.

I need a component to search dynamically based on passed object attributes value, and not changed by the time.

For example if I have Bank that has (id, name, address, and state object), and I have created a bank object with name and address has values construct the JPQL SELECT statement (SELECT b FROM Bank b where b.name = :name AND b.address = :address) and search by it and so on.

I have developed a component to implement the above case called DynamicQueryBuilder with advanced techniques, and configurations.

In this article I will describe how I built this component with support of annotation, reflection and generics. In the code snippets you will find a brief description about each line of code and methods, the annotation developed to support the component and I will describe also the overall functionality of the component and how to call it to work dynamically…

Tuesday, February 28, 2012

Blog: How to professionally highlight your blog code using (Syntax Highlighting)

Hello everyone

Recently I have searched for a way to automatically keep my code snippets formatted and colorized with proper highlighting & syntax, without painful self-highlighting way, and then Blogger/Wordpress doesn't have the immediate solution out here!

I found an excellent open source tool called Syntax Highlighter is available.
This is ready to use out of box 100% Javascript based SyntaxHighlighter with extensive features & multiple other options.

SyntaxHighlighter can be either downloaded & used on your own webserver or if you have a blog on Blogger, this can be directly used as well.

To downloaded SyntaxHighlighter for your own personal Webserver/Hosted
site: http://alexgorbatchev.com/wiki/SyntaxHighlighter:Download
Configuration Steps: http://alexgorbatchev.com/wiki/SyntaxHighlighter:Configuration
Brush Aliases: http://alexgorbatchev.com/wiki/SyntaxHighlighter:Brushes


Sunday, February 5, 2012

Database: Oracle NoSQL Database in 5 Minutes

Inspired by some other "Getting started in 5 minutes" guides, we now have a Quick Start Guide for Oracle NoSQL Database.  kvlite, the single process Oracle NoSQL Database, makes it incredibly easy to get up and running.  I have to say the standard disclaimer: kvlite is only meant for kicking the tires on the API.  It is not meant for any kind of performance evaluation or production use.

Saturday, December 10, 2011

AIR: Adobe AIR with SQLite database

An AIR application that doesn’t need to store data on your computer is extremely rare. That is why I have created a basic application that should help you understand and learn how you can store data in SQLite database. 

The example is really basic but it should get you an idea on how to do it.

SQLiteExample.mxml

<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                       xmlns:s="library://ns.adobe.com/flex/spark" 
                       xmlns:mx="library://ns.adobe.com/flex/mx"
                       creationComplete="start()" width="800" height="600" viewSourceURL="srcview/index.html">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    
    <fx:Script source="SQLiteCode.as"/>
    
    <s:Label x="10" y="20" text="First name:"/>
    <s:Button x="394" y="10" label="Add" click="addItem()"/>
    <s:Label x="202" y="20" text="Last name:"/>
    <s:Button label="Remove selected" y="10" x="472" click="remove()" enabled="{dg.selectedIndex != -1}"/>
    <s:TextInput x="77" y="10" width="117" id="first_name"/>
    <s:TextInput x="268" y="10" width="117" id="last_name"/>
    <mx:DataGrid id="dg" left="10" right="10" top="40" bottom="10" dataProvider="{dp}">
        <mx:columns>
            <mx:DataGridColumn headerText="Index:" dataField="id"/>
            <mx:DataGridColumn headerText="First name" dataField="first_name"/>
            <mx:DataGridColumn headerText="Last name" dataField="last_name"/>
        </mx:columns>
    </mx:DataGrid>
</s:WindowedApplication>

SQLiteCode.as

import flash.data.SQLStatement;
import flash.errors.SQLError;
import flash.events.Event;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.utils.Timer;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.utils.ObjectUtil;

import org.osmf.events.TimeEvent;

// sqlc is a variable we need to define the connection to our database
private var sqlc:SQLConnection = new SQLConnection();
// sqlc is an SQLStatment which we need to execute our sql commands
private var sqls:SQLStatement = new SQLStatement();
/* 
   ArrayCollection used as a data provider for the datagrid. It has to 
   be bindable so that data in datagrid changes automatically when we change 
   the ArrayCollection.
*/
[Bindable]
private var dp:ArrayCollection = new ArrayCollection();
/* 
    function we call at the begining when application has finished loading and bulding itself.
*/
private function start():void
{
    /* 
      first we need to set the file class for our database (in this example test.db). 

      If the Database doesn't exists it will be created when we open it.
       */
    var db:File = File.applicationStorageDirectory.resolvePath("test.db");
    // after we set the file for our database we need to open it with our SQLConnection.
    sqlc.openAsync(db);
    /* 
      we need to set some event listeners so we know if we get an sql error, 
      when the database is fully opened and to know when we recive a resault from an sql statment. 
      The last one is used to read data out of database.
       */
    sqlc.addEventListener(SQLEvent.OPEN, db_opened);
    sqlc.addEventListener(SQLErrorEvent.ERRORerror);
    sqls.addEventListener(SQLErrorEvent.ERRORerror);
    sqls.addEventListener(SQLEvent.RESULT, result);
}
private function db_opened(e:SQLEvent):void
{
    /* 
      when the database is opened we need to link the SQLStatment to our 
      SQLConnection, so that sql statments for the right database.
     if you don't set this connection you will get an error when you 
      execute sql statement.
       */    sqls.sqlConnection = sqlc;
    /*
      in property text of our SQLStatment we write our sql command. 
      We can also combine sql statments in our text property so that more than one 
      statement can be executed at a time.
     in this sql statment we create table in our database with name 
     "test_table" with three columns (id, first_name and last_name). Id is an 
     integer that is auto incremented when each item is added. First_name and last_name
     are columns in which we can store text.
     If you want to know more about sql statements search the web.
        */
    sqls.text = "CREATE TABLE IF NOT EXISTS test_table 
                 ( id INTEGER PRIMARY KEY AUTOINCREMENT, first_name TEXT, last_name TEXT);";
    /*
      after we have connected sql statement to our sql connection and written 
      our sql commands we also need to execute our sql statment.
      nothing will change in database until we execute sql statement.
       */    sqls.execute();
    /* 
     after we load the database and create the table if it doesn't already 
     exists, we call refresh method which i have created to populate our datagrid
        */    refresh();
}
// function to add item to our database
private function addItem():void
{
    // in this sql statment we add item at the end of our table with values 
    // first_name.text in column first_name and last_name.text for column last_name
    sqls.text = "INSERT INTO test_table (first_name, last_name) 
                 VALUES('"+first_name.text+"','"+last_name.text+"');";
    sqls.execute();
    
    refresh();
}

// function to call when we want to refresh the data in datagrid
private function refresh(e:TimerEvent = null):void
{
    // timer object which we need if sql statment is still executing so that we 
    // can try again after 10 milliseconds.
    var timer:Timer = new Timer(10,1);
    timer.addEventListener(TimerEvent.TIMER, refresh);
    // we need to check if our sql statment is still executing our last sql command. 
    // If so we use Timer to try again in 10 milliseconds. If we wouldn't check we 
    // could get an error because SQLStatment can't execute two statments at the same time.
    if ( !sqls.executing )
    {
        // sql statment which returns all the data from our "test_table". 
        // To retrive only data from first_name and last_name columns we would use 
        // "SELECT first_name,last_name FROM test_table"
        sqls.text = "SELECT * FROM test_table";
        sqls.execute();
    }
    else
    {
        timer.start();
    }
}

// method that gets called if we recive some resaults from our sql commands.
// this method would also get called for sql statments to insert item and 
// to create table but in this case sqls.getResault().data would be null.
private function resault(e:SQLEvent):void
{
    // with sqls.getResault().data we get the array of objects for each row out of our database
    var data:Array = sqls.getResult().data;
    // we pass the array of objects to our data provider to fill the datagrid
    dp = new ArrayCollection(data);
}

// method to remove row from database.
private function remove():void
{
    // sql statement to delete from our test_table the row that has the 
    // same number in number column as our selected row from datagrid
    sqls.text = "DELETE FROM test_table WHERE id="+dp[dg.selectedIndex].id;
    sqls.execute();
    refresh();
}
// method which gets called when we recive an error  from sql connection 
// or sql statement and displays the error in the alert
private function error(e:SQLErrorEvent):void
{
    Alert.show(e.toString());
}