Sunday, 28 August 2011

SQL Loop through records and replace


use DB_Name
DECLARE @var_1 as nvarchar(300)
DECLARE @var_2 as int --DECLARE @VariableName as Variable DataType
                                              --You can DECLARE many variable seperated by comma
                                              --to add another variable to the previous declaration use this example
                                              --,
                                              --@Variable2 as char

                             
DECLARE cursor_ CURSOR FOR   --declare the cursor
SELECT    primary_key_column_name , column2         --write a correct select statmen
FROM dbo.TableName

OPEN cursor_      --Open the cursor
FETCH NEXT FROM cursor_ INTO @var_1, @var_2  -- filling the variables using the cursor
WHILE (@@FETCH_STATUS = 0)        --Looping through the cursor
  BEGIN                             --Write you code here to do what you want


if(@var_2='null' or @var_2='NULL' OR @var_2='Null')

   UPDATE dbo.Channels SET var_2=column_name_to_be_replaced_with
   WHERE primary_key_column_name=@var_1

   FETCH NEXT FROM cursor_ INTO @chanID_, @chanName_Ar_ --To move the cursor to the next row
  END
  CLOSE cursor_                       --You have to close the cursor
  DEALLOCATE cursor_                  --You have to free the memory

Thursday, 25 August 2011

Read Arabic text file into Sql server 2008 table

*  Save your text file as "unuicode"
*  use ntext, nvarchar, nchar as Columns Datatypes

* The DB collation should be Arabic_100_CI_AS

use this query:


use DBname
BULK INSERT  dbo.TableName FROM 'c:\TextFileName.txt' 
WITH (    

      FIELDTERMINATOR = '\t',
      ROWTERMINATOR = 'q'    
);


\t: is the delimiter between columns
q: is the delimiter between rows

Sunday, 7 August 2011

How to start GlassFish 3.0 at boot in windows?

You may want to start your GlassFish 3.0 Server automatically at windows boot (Start). to do that
Follow these instructions:

1) Go to the installation location and open the bin folder, this is the default bath
C:\glassfish3\bin

2) Double click on "asadmin.bat" file
3) Type "start-domain myDomain" and press enter
4) To create the windows service which starts the server automatically at windows boot
type the command " create-service" and the server domain which you want to create a service for it;
 " create-service myDomain" and press Enter.
5) You need to install the service on Windows
    I) open cmd and type "sc create domain1 start= auto binPath= C:\mapviewer11g_qs\glassfish3\glassfish\domains\domain1\bin\domain1Service.exe"


or II) use the following procedure
    a) go to .net framework C:\Windows\Microsoft.NET
    b) search about installutil.exe
    c) if their is no .net framework installed, you need to install .net 4 or later to
        find installutil.exe
    d) Copy the path of installutil.exe  and past it at the end of the "Path" system
        variable
    e) Open cmd as administrator and cd into the bin directory of the domain which you
        created a service for it and type installutil sericeName.exe and hit enter
     f) Restart your PC.
     g) Configure your Service from system services


See the following snapshot

















Congratulations, your server runs automatically

Note: to view all creating commands type "create" and press enter, and so on for any word
Mohammad Abu Hmead

How to start GlassFish 3.0 at boot time in windows?

You may want to start your GlassFish 3.0 Server automatically at windows boot (Start). to do that
Follow these instructions:

1) Go to the installation location and open the bin folder, this is the default bath
C:\glassfish3\bin

2) Double click on "asadmin.bat" file
3) Type "start-domain myDomain" and press enter
4) To create the windows service which starts the server automatically at windows boot
type the command "create-service" and the server domain which you want to create a service for it;
 "create-services myDomain" and press Enter.
4) Restart your PC.

See the following snapshot

















Congratulations, your server runs automatically

Note: to view all creating commands type "create" and press enter, and so on for any word
Mohammad Abu Hmead

Thursday, 21 July 2011

Creat Servlet and Connect it to MS SQL server


1) Install Netbeans 6.9 or later
2) Download GlassFish from this site
install GlassFish, it will run easy
3) Run NetBeans IDE and view Services window 


Right Click on servers the click on "add server.."

Type instead of x the version of the GlassFish you want to add
the press Next and type the link of the GlassFish installation folder 
press Next and Select the domain and press Finish
** Now your GlassFish Created 

4) Now you have to start the server by right click on GlassFish 3.1 and click start 
if the server didn't  start the solution is bellow

5) Creating GlassFish Domain
open your  glass fish directory and open bin folder 
double click on "asadmin" it will run and type "domain" then an error list will shown like the figure bellow 

never mind, just I want to show you how you can get correct commands 
now type "create-domain domain2" and wait for response 

back to netbeans and repeat step 3 but choose domain2 and run the server

---------------------------------------------
Now we want to configure MSSQL server
1) install SQL server 2005 or later
2) Create your DB with windows authentications 
3) Create new user with Sql authentications with password and select the DB to be shown to this user 
4) Go to DB and right Click and choose properties and press on Permissions and select the user and check all CheckBoxes under Grant Header like the figure bellow 

5) Now you want to know the port number on which the SQL server listen to
by doing like the two figures bellow

from the previous figure you can get the port.


-------------------------------------------
Now Creating Servlet 

1) Run Netbeans and press on "File" tab and press on "New Project" 
2) Select Java Web from Categories and Web Application from Projects
3) Type your project name and directory and the libraries directory 
4) Choose GlassFish and JEE 
5) Do like the figure bellow (let all of them empty)

Click finish, now you have a web project

*** Creating Servlet
on project name right click and select  new Servlet
Do like the bellow two figures 



Press finish and edit the 

Add the sql db driver into libraries 
downloadable from this site http://www.mediafire.com/?3ycmaelhoot

Look at the example bellow

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.servlet.annotation.WebServlet;

/**
 *
 * @author Mohammad
 */
//this to call the servlet from an ip address
//http://ipaddress:port/defaultSite/ServletCallableName

@WebServlet(name = "ServletCallableName", urlPatterns = {"/ServletCallableName"})

public class NewServlet extends HttpServlet {

    private Connection conn;
    private PrintWriter printWriter;
    private StringBuffer stringBuffer;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String ua = request.getHeader("User-Agent");      

        stringBuffer = new StringBuffer();
       
            CallableStatement callableStatment = null;

            try {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;"//1433 sql port look at    
//figures bellow
                        + "databaseName=WhoWantsToBeMillionaireQs;user=mohammad;password=moh");

                callableStatment = conn.prepareCall("{call get_rando_rows(?)}");//call get_rando_rows: procedure name created on Sql serve DB, takes one parameter, the procedure runs 3 select statments and returns 3 results as three tables 
                callableStatment.setString("Count", "5");//the procedure parameter 

                boolean isExecuted = callableStatment.execute();//to execute the query 

                int rsCount = 0;
                try {

                    do {
                        if (isExecuted) {
                            ResultSet rs = callableStatment.getResultSet();
                            rsCount++;

                            ResultSetMetaData rsmd = rs.getMetaData();
                            int numOfColumns = rsmd.getColumnCount();
                            while (rs.next()) {
                                for (int i = 1; i <= numOfColumns; i++) {
                                    stringBuffer.append(rs.getString(i));
                                    stringBuffer.append("|#|");
                                }
                            }
                            rs.close();
                            System.out.println();
                            isExecuted = callableStatment.getMoreResults();
                        }
                    } while (isExecuted);
                    callableStatment.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } catch (SQLException ex) {
                stringBuffer.append("  SQL Exception.  ");
                stringBuffer.append(ex.getMessage());
            } catch (ClassNotFoundException cex) {
                stringBuffer.append("  Class Not Found Exception  ");
                stringBuffer.append(cex.getMessage());
            } catch (Exception ex) {
                stringBuffer.append("Unknown Exception  ");
                stringBuffer.append(ex.getMessage());

            }
       
        response.setContentType("text/plain");
        printWriter = response.getWriter();
        printWriter.print(stringBuffer.toString());
        printWriter.close();

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


Mohammad Abu Hmead 
Palestine 
21.07.2011
01:43 AM

Sunday, 17 July 2011

Connection between Java and SQL Server

Hint: Use sqljdbc4.jar


package server;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import javax.servlet.annotation.WebServlet;
/**
 *
 * @author Mohammad
 */
@WebServlet(name = "viewFromSQL", urlPatterns = {"/viewFromSQL"})
public class EmailConnectedtoSQLServer2008 extends HttpServlet {
Connection theConnection;
 private ServletConfig config;
 public void init(ServletConfig config)
  throws ServletException{
  this.config=config;
 }
    public void service (HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
         
   HttpSession session = req.getSession(true);
   res.setContentType("text/html");
   PrintWriter out = res.getWriter();

        out.println("<HTML><HEAD><TITLE>Emai List.</TITLE>");
   out.println("</HEAD>");
   out.println("<BODY bgColor=blanchedalmond text=#008000 topMargin=0>");
        out.println("<P align=center><FONT face=Helvetica><FONT color=fuchsia style=\"BACKGROUND-COLOR: white\"><BIG><BIG>List of E-mail addresses.</BIG></BIG></FONT></P>");
   out.println("<P align=center>");
        out.println("<TABLE align=center border=1 cellPadding=1 cellSpacing=1 width=\"75%\">");
 
        out.println("<TR>");
        out.println("<TD>Name</TD>");
        out.println("<TD>E-mail</TD>");
        out.println("<TD>Website</TD></TR>");
 try{
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");//Loading Sun's JDBC ODBC Driver
            theConnection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;" +
         "databaseName=email;user=moh;password=123"); //Connect to emaildb Data source
            out.println("<br> DATABASE NAME IS:" 
                    + theConnection.getMetaData().getDatabaseProductName()+"</br>");
            Statement theStatement=theConnection.createStatement();
            ResultSet theResult=theStatement.executeQuery("SELECT * FROM emaillists"); //Select all records from emaillists table.
 
              while(theResult.next()) //Fetch all the records and print in table
  {
                   
     out.println();
       out.println("<TR>");
       out.println("<TD>" + theResult.getString(1) + "</TD>");
       out.println("<TD>" + theResult.getString(2) + "</TD>");
   String s=theResult.getString(3);
       out.println("<TD><a href=" + s + ">" + s + "</a></TD>");
       out.println("</TR>");

  }
            theResult.close();//Close the result set
            theStatement.close();//Close statement
            theConnection.close(); //Close database Connection
      }catch(Exception e){
  out.println(e.getMessage());//Print trapped error.
 }
 
       out.println("</TABLE></P>");
       out.println("<P>&nbsp;</P></FONT></BODY></HTML>");

 }
 public void destroy(){

 }
}

JAVA to MS Access Connection (JDBC-ODBC bridge)