2013年10月31日 星期四

java-mysql-utf8-sample (work in Linux Command Line)



mysql> status
--------------
mysql  Ver 14.14 Distrib 5.5.31, for debian-linux-gnu (x86_64) using readline 6.2

Connection id:          63
Current database:       hr
Current user:           root@localhost
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         5.5.32-0ubuntu0.12.04.1 (Ubuntu)
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:            /var/run/mysqld/mysqld.sock
Uptime:                 2 hours 44 min 23 sec

Threads: 1  Questions: 7459  Slow queries: 0  Opens: 330  Flush tables: 1  Open tables: 85  Queries per second avg: 0.756
--------------

MysqlJDBC.java for insert , update purpose

// create table te22t (id numeric(5), name char(50) , aa smallint,bb smallint,cc smallint);
// root@it-dev:/hr/WEB-INF/classes# java NewJDBC te22t

import java.sql.*;

public class MysqlJDBC {
  static String classname = "com.mysql.jdbc.Driver";
  static String jdbcURL = "jdbc:mysql://localhost/test";
  static String UID = "userName";
  static String PWD = "passWord";
  static Connection conn = null;

  public static void main( String argv[] ) {
    // initialize query string
    if(argv.length != 1) {
      System.out.println("Usage: java NewJDBC ");
      System.out.println("   ex. java NewJDBC Product");
      System.exit(2);
    }
    String aQuery = "select * from " + argv[0];
    String iSQL = "insert into " + argv[0] + " values(5,'繁體',14.5,2)";
iSQL="insert into te22t  values(5,'a',14,5,2);";
    String uSQL = "update " + argv[0] + " set Name='鍵盤' where ID=5";
    String dSQL = "delete from " + argv[0] + " where ID=5";

    try {
      // load the JDBC-ODBC bridge driver
      Class.forName(classname).newInstance();

      // connect to Database
      conn = DriverManager.getConnection(jdbcURL,UID,PWD);

      // Display current content
      System.out.println("Display current content");
      ShowResults(aQuery);

      // Insert a new record
      System.out.println("\nInserting a new record .....");
      InsertNew(iSQL);
      ShowResults(aQuery);

      // Update record
      System.out.println("\nUpdateing a record .....");
      UpdateNew(uSQL);
      ShowResults(aQuery);

      // Delete record
      System.out.println("\nDeleting a record .....");
      //20131101 DeleteNew(dSQL);
      ShowResults(aQuery);

      conn.close();
    } catch (Exception sqle) {
      System.out.println(sqle);
      System.exit(1);
    }
  }

  private static void DeleteNew(String dSQL) {
    try {
      Statement aStatement = conn.createStatement();
      aStatement.executeUpdate(dSQL);
    } catch (Exception e) {
      System.out.println("Delete Error: " + e);
      System.exit(1);
    }
  }

  private static void UpdateNew(String uSQL) {
    try {
      Statement aStatement = conn.createStatement();

      // ISO-8859-1 其實就是 latin1 的編碼
      // 以下的目的是要把 UTF-8 的字串轉成 byte array 然後再轉成符合
      // 目前的 latin1 的編碼
      // aStatement.executeUpdate(new String(uSQL.getBytes("UTF-8"), "ISO-8859-1"));
      // test in Linux 
     // aStatement.executeUpdate(new String(uSQL.getBytes("LinuxCharCode"), "MySqlCode"));
 aStatement.executeUpdate(new String(uSQL.getBytes("UTF-8"), "UTF-8"));
    } catch (Exception e) {
      System.out.println("Update Error: " + e);
      System.exit(1);
    }
  }

  private static void InsertNew(String iSQL) {
    try {
      Statement aStatement = conn.createStatement();
      //aStatement.executeUpdate(new String(iSQL.getBytes("UTF-8"), "ISO-8859-1"));
 aStatement.executeUpdate(new String(iSQL.getBytes("UTF-8"), "UTF-8"));
    } catch (Exception e) {
      System.out.println("Insert Error: " + e);
      System.exit(1);
    }
  }


  private static void ShowResults(String aQuery) {
    try {
      // Construct a SQL statement and submit it
      Statement aStatement = conn.createStatement();
      ResultSet rs = aStatement.executeQuery(aQuery);

      // Get info about the query results
      ResultSetMetaData rsmeta = rs.getMetaData();
      int cols = rsmeta.getColumnCount();

      // Display column headers
      for(int i=1; i<=cols; i++) {
        if(i > 1) System.out.print("\t");
        System.out.print(rsmeta.getColumnLabel(i));
      }
      System.out.print("\n");

      // Display query results.
      while(rs.next()) {
        for(int i=1; i<=cols; i++) {
          if (i > 1) System.out.print("\t");
          //System.out.print(new String(rs.getString(i).getBytes("ISO-8859-1"),"UTF-8"));
 System.out.print(new String(rs.getString(i).getBytes("UTF-8"),"UTF-8"));
        }
        System.out.print("\n");
      }

      // Clean up
      rs.close();
      aStatement.close();
    }
    // a better exception handling can be used here.
    catch (Exception e) {
      System.out.println("Exception Occurs.");
    }
  }
}

asp-next-line



asp for each in array

inf http://webcheatsheet.com/asp/loops.php

<%
Dim bookTypes(7) 'creates first array
bookTypes(0)="Classic"
bookTypes(1)="Information Books"
bookTypes(2)="Fantasy"
bookTypes(3)="Mystery"
bookTypes(4)="Poetry"
bookTypes(5)="Humor"
bookTypes(6)="Biography"
bookTypes(7)="Fiction"

Dim arrCars(4) 'creates second array
arrCars(0)="BMW"
arrCars(1)="Mercedes"
arrCars(2)="Audi"
arrCars(3)="Bentley"
arrCars(4)="Mini"

Sub createList(some_array) 'takes an array and creates drop-down list
  dim i
  response.write("<select name=""mylist"">" & vbCrLf) 'vbCrLf stands for Carriage Return and Line Feed
  For Each item in some_array
     response.write("<option value=" & i & ">" & item & "</option>" & vbCrLf)
     i = i + 1
  Next 'repeat the code and move on to the next value of i
  response.write("</select>")
End Sub

'Now let's call the sub and print out our lists on the screen
Call createList(bookTypes) 'takes bookTypes array as an argument
Call createList(arrcars) 'takes arrCars array as an argument
%>

asp-for-each-in-array

asp for each in array
asp-for-loop
asp for all in
asp-for-all-in

inf http://webcheatsheet.com/asp/loops.php

<%
Dim bookTypes(7) 'creates first array
bookTypes(0)="Classic"
bookTypes(1)="Information Books"
bookTypes(2)="Fantasy"
bookTypes(3)="Mystery"
bookTypes(4)="Poetry"
bookTypes(5)="Humor"
bookTypes(6)="Biography"
bookTypes(7)="Fiction"

Dim arrCars(4) 'creates second array
arrCars(0)="BMW"
arrCars(1)="Mercedes"
arrCars(2)="Audi"
arrCars(3)="Bentley"
arrCars(4)="Mini"

Sub createList(some_array) 'takes an array and creates drop-down list
  dim i
  response.write("<select name=""mylist"">" & vbCrLf) 'vbCrLf stands for Carriage Return and Line Feed
  For Each item in some_array
     response.write("<option value=" & i & ">" & item & "</option>" & vbCrLf)
     i = i + 1
  Next 'repeat the code and move on to the next value of i
  response.write("</select>")
End Sub

'Now let's call the sub and print out our lists on the screen
Call createList(bookTypes) 'takes bookTypes array as an argument
Call createList(arrcars) 'takes arrCars array as an argument
%>

asp-procedure asp-method asp-function asp-sub

inf : http://webcheatsheet.com/asp/loops.php

<%
Dim bookTypes(7) 'creates first array
bookTypes(0)="Classic"
bookTypes(1)="Information Books"
bookTypes(2)="Fantasy"
bookTypes(3)="Mystery"
bookTypes(4)="Poetry"
bookTypes(5)="Humor"
bookTypes(6)="Biography"
bookTypes(7)="Fiction"

Dim arrCars(4) 'creates second array
arrCars(0)="BMW"
arrCars(1)="Mercedes"
arrCars(2)="Audi"
arrCars(3)="Bentley"
arrCars(4)="Mini"

Sub createList(some_array)
  dim i
  response.write("<select name=""mylist"">" & vbCrLf) 'vbCrLf stands for Carriage Return and Line Feed
  For Each item in some_array
     response.write("<option value=" & i & ">" & item & "</option>" & vbCrLf)
     i = i + 1
  Next 'repeat the code and move on to the next value of i
  response.write("</select>")
End Sub




'Now let's call the sub and print out our lists on the screen
Call createList(bookTypes) 'takes bookTypes array as an argument
Call createList(arrcars) 'takes arrCars array as an argument
%>

2013年10月30日 星期三

itext-tutorial

itext-tutorial


http://itextpdf.com/examples/iia.php?id=79

itext-function-control java-pdf java-print



import com.itextpdf.text.Anchor;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.PageSize;

public class MainClass {

  public static void main(String[] args) throws Exception {
    Document document = new Document();


        Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
        PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );

    PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    document.open();
    Chunk c = new Chunk("this is a test");
    float w = c.getWidthPoint();
    Paragraph p = new Paragraph("The width of the chunk: '");
    p.add(c);
    p.add("' is ");
 
    p.add(String.valueOf(w));
    p.add(" points or ");
    p.add(String.valueOf(w / 72f));
    p.add(" inches or ");
    p.add(String.valueOf(w / 72f * 2.54f));
    p.add(" cm.");
    document.add(p);
    document.add(Chunk.NEWLINE);  // New Line new space line





    document.add(c);
document.add(table);


table = new PdfPTable(3);  ////////////////////////////// columns of Report
table.setWidths(new int[]{30,850,260}); ////////////////////// column widths
table.setWidthPercentage(100); //////////////////////////////////// tables width 100%
table.getDefaultCell().setBorder(0); ////////////////////////////// border-width to 0

c1 = new PdfPCell(new Phrase("3", font8));
c1.setBorder(0);
c1.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(c1); //1
c1 = new PdfPCell(new Phrase("(a) H.K.Identity Card Number : ", font8));
c1.setBorder(0);
c1.setHorizontalAlignment(Element.ALIGN_LEFT);
table.addCell(c1); //2
c1 = new PdfPCell(new Phrase(dRaws[i][1], font8));
c1.setBorder(0);
c1.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(c1);

    document.close();
  }
}



xxxxxxxxxxxxxxx


public static void main(String args[]) {
    try {
        // create a new document
        Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
        PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );

        document.open();

        document.add( new Paragraph( "Hello, World!" ) );
        document.add( new Paragraph( "Hello, World!" ) );

        // add a couple of blank lines
        document.add( Chunk.NEWLINE );
        document.add( Chunk.NEWLINE );

        // add one more line with text
        document.add( new Paragraph( "Hello, World!" ) );

        document.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

itext-template


inf: http://stackoverflow.com/questions/4158336/how-to-insert-blank-lines-in-pdf-using-itext


public static void main(String args[]) {
    try {
        // create a new document
        Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
        PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );

        document.open();

        document.add( new Paragraph( "Hello, World!" ) );
        document.add( new Paragraph( "Hello, World!" ) );

        // add a couple of blank lines
        document.add( Chunk.NEWLINE );
        document.add( Chunk.NEWLINE );

        // add one more line with text
        document.add( new Paragraph( "Hello, World!" ) );

        document.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

asp-int


http://stackoverflow.com/questions/20675/asp-vbscript-int-vs-cint


asp integer

Script:
wscript.echo 40.91 * 100
wscript.echo Int(40.91 * 100)
wscript.echo CInt(40.91 * 100)
result:
4091
4090   (????)
4091

asp-string2integer

asp string to integer to numeric
asp str2int
asp strtoint
asp-str-to-int 
asp-val()



Dim A, B, C
Set rs = Server.CreateObject("ADODB.Recordset")
strSql = "Exec [dbo].[some_sp] IND"
rs.open strSql,CN,3,3

Do While Not rs.EOF

'these columns are returned as decimal(10,2) format
A = rs("col1")
B = rs("col2")

rs.MoveNext
Loop

C = A + B 'i get type mismatch error here

Variables in ASP/VBScript are just variant types so you may need to convert the values explicitly.
C = CDbl(A) + CDbl(B)

2013年10月29日 星期二

java-zip-winzip-winrar java archieve

inf : http://stackoverflow.com/questions/4773778/creating-zip-archive-in-java

import java.io.*;
import java.util.zip.*;
public class ZipCreateExample{
    public static void main(String[] args)  throws Exception  
        // input file 
        FileInputStream in = new FileInputStream("F:/sometxt.txt");

        // out put file 
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream("F:/tmp.zip"));

        // name the file inside the zip  file 
        out.putNextEntry(new ZipEntry("zippedjava.txt")); 

        // buffer size
        byte[] b = new byte[1024];
        int count;

        while ((count = in.read(b)) > 0) {
            System.out.println();
            out.write(b, 0, count);
        }
        out.close();
        in.close();
    }
}

asp-write-file

iis-write file
iis-file

inf : http://www.w3schools.com/asp/met_write.asp


<%
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject") 
set f=fs.CreateTextFile("c:\test.txt",true)
f.write("Hello World!")
f.write("How are you today?")
f.close
set f=nothing
set fs=nothing
%>


Set permission

To been able to run a public asp.net site with IIS, 
each file on the directory must have permissions for two accounts.

One account that is permitted for public access, 

and the account that assigned to that application pool have.

http://stackoverflow.com/questions/16677887/how-to-set-correct-file-permissions-for-asp-net-on-iis

html-download html-download-button

Button
http://stackoverflow.com/questions/11620698/how-to-trigger-a-file-download-when-clicking-an-html-button-or-javascript

http://webitect.net/design/20-effective-download-buttons-plus-tips-and-examples/

<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>

$("#fileRequest").click(function() {
    // // hope the server sets Content-Disposition: attachment!
    window.location = 'file.doc';
});

<a download='file'>Download</a>

<a href="file.doc" class="button" style="text-decoration:none">
  Download!
</a>

<a href="http://www.example.com/folder1/file.doc">Download</a>

<input type="button" value="Download Now!" onclick="window.location = 'file.doc';">

<button type="submit" onclick="window.open('file.doc')">Download!</button>
function Download(){
  window.open('file.doc');
}

<a href="file.doc">Download!</a>

<input type="button" value="Download!">
<button>Download!</button>

<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>

$("#fileRequest").click(function() {
    // // hope the server sets Content-Disposition: attachment!
    window.location = 'file.doc';
});

<a download='file'>Download</a>

<a href="file.doc" class="button">
  Download!
</a>
.button
{
  /*Make your button look cool.*/
}

<input type="button" value="Download Now!" onclick="window.location = 'file.doc';">

<button type="submit" onclick="window.open('file.doc')">Download!</button>
function Download(){
  window.open('file.doc');
}

2013年10月28日 星期一

mysql-create-table-from-select -memory 20141106 create table auto_increment

create table REPORT (DESCRIPTION CHAR(50),RECORDID  int(10) unsigned NOT NULL AUTO_INCREMENT,PRIMARY KEY (`RECORDID`));
ALTER TABLE REPORT ADD COLUMN DOC_NO INT;

INSERT INTO REPORT (DESCRIPTION) VALUES ('GRN OS');


select-from-select

CREATE TABLE CUSTOMER_OLD SELECT * FROM CUSTOMER;

create table merget as select * from table1 union select * from table2

create table price (id int, pricelist int) type=memory
create table if not exists tableName(
id (20) not null 
,firstname verchar(20) not null
,primary key (2d)) type memory; 

create table if not exists tableName(id (20) not null, firstName varchar(20) not null primary key(id) type = memory; 

CREATE TABLE suppliers
  AS (SELECT id, address, city, state, zip
      FROM companies


 create table ROLE (DESCRIPTION CHAR(50),RECORDID  int(10) unsigned NOT NULL AUTO_INCREMENT,PRIMARY KEY (`RECORDID`));

mysql-group group by month


select sum(grosspay),datestart,year(datestart)*12+month(datestart) from payroll group by year(datestart)*12+month(datestart);



select sum(grosspay),datestart,year(datestart)*12+month(datestart)
from payroll
where year(datestart)*12+month(datestart)>24163
group by year(datestart)*12+month(datestart);

asp-function

http://www.w3schools.com/vbscript/vbscript_ref_functions.asp

html-selected html-combo yyyy mm



<label>From YYYY
<select id="FYYYY" name="FYYYY">
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012" selected>2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
</label>

<label>MM
<select id="FMM" name="FMM">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11" selected>11</option>
<option value="12">12</option>
</select>
</label>
<!-- label>TO YYYY<input type="text" name="TYYYY" id="TYYYY" value=2013></label -->
<!-- label>MM<input type="text" name="TMM" id="TMM" value=9></label -->

<label>To YYYY
<select id="TYYYY" name="TYYYY">
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013" selected>2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
</select>
</label>

<label>MM
<select id="TMM" name="TMM">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4" selected>4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</label>

2013年10月27日 星期日

html-input-simple

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  "http://www.w3.org/TR/html4/loose.dtd">  
<html>

<head>
<title>HTML Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>

<form action="example_input.php" method="post">
<p>
 <label>Enter Text <input type="text" name="texttest"></label>
 <br><input type="submit" value="Send"> <input type="reset">
</p>
</form>

</body>
</html>              

html-exit

<input type="button" id="exit" name="exit" value="EXIT" style="display:inline; float:right;" >

html-caption, form-caption

html-page-caption page-header pagehearder form-caption

<div id="browserInfo" style="overflow:auto;margin:auto;display:block;">
<span style="background-color: #4378b6; color: white;
float: left; height: 20px; margin-bottom: 0; padding-left:5px ; width: 100%;">
<input style="display:none;" value="Menu Listing"/>
Menu Listing
</span>
</div>

onclick-iframe

onclick iframe


<td valign="top" width=100% >
<iframe style="margin-left:0; padking:0 ; height:600px;" name="iframe2" id="iframe2"  width=100% src="http://www.google.com/"  ></iframe>
</td>


'Response.Write("<a style='width:160px; ; font-size:12px; margin-left:-5px;' onclick="&chr(34)&"$('#iframe2').prop('src','"&SP&L&"');"&chr(34)&">"&S)

asp-date()-hour()


var d = new Date();
var mm = d.getMonth()+1;
var yyyy = d.getFullYear();
var dd = d.getDate()


<!DOCTYPE html>
<html>
<body>
<%
dim h
h=hour(now())

response.write("<p>" & now())
response.write("</p>")
If h<12 then
   response.write("Good Morning!")
else
   response.write("Good day!")
end if
%>

</body>
</html>

asp-array


<%
Dim myFixedArray(3) 'Fixed size array
myFixedArray(0) = "Albert Einstein"
myFixedArray(1) = "Mother Teresa"
myFixedArray(2) = "Bill Gates"
myFixedArray(3) = "Martin Luther King Jr."
For Each item In myFixedArray
Response.Write(item & "<br />")
Next
%>

2013年10月25日 星期五

java-DAO-sample with connector




STEP 1 CREATE TABLE

DROP TABLE commodity;
CREATE TABLE commodity (
  commodityid int(11) NOT NULL auto_increment,
  commodityName varchar(30) default NULL,
  price decimal(10,2) default NULL,
  agio decimal(4,3) default NULL,
  PRIMARY KEY (commodityid)
)


STEP 2 DAO Interface

\WebRoot\CommodityDAO.java

package com.ProjectName.dao;
import.java.util,List;
import.com.ProjectName.bean.Commodity;
public interface CommodityDAO {
  public void addCommodity(Commodity commodity);
  public void updateCommodity(Commodity commodity);
  public void deleteCommodity(Commodity commodity);
  public List<Commodity> findAllCommodity();
  public Commodity findCommodityByID(int commidtyId);
}


STEP 3 DAO implement

public class CommodityDAOImpl implements CommodityDAO{

  public void addCommodity(Commodity commodity){
    Connection conn=DBConnection.getConnection();
    String addSQL="insert into commodity(commodityName,price,agio) values(?,?,?)";
//  String updateSQL="update commodity set commodityName=?prce=?,ago=? where commodityid=?";
//  String updateSQL="delete from commodity where commodityid=?";

    PreparsedStatment pstmt=null;
    try{
        pstmt=conn.prepareStatement(addSQL);
        pstmt.setString(1,commodity.getCommodityName());
        pstmt.setDouble(2,commodity.getPrice());
        pstmt.setDouble(3,commodity.getAgio());
        //pstmt.setInt(4,commodity.getCommodity());
        pstmt.executeUpdate();
  } catch (SQLException e){
        e.printStackTrace();
  } finally {
        DBConnection.close(pstmt);
        DBConnection.close(conn);
  }
}

 publicList<Commodity> findAllCommodity() {
   Connection conn=DBConnection.getConnection();
   String updateSQL="Select * from commodity";
   PreparedStatement pstmt=null;
    List<Commodity>commodityList=new ArrayList<Commodity>();
    try {
      pstmt=conn.prepareStatement(updateSQL);
      ResultSet rs=pstmt.executeQuery();
      while(rs.next()) {
            Commodity commoidty=new Commoidty();
            commoidty.setCommodityId(rs.getInt(1));
            commoidty.setCommodityName(rs.getString(2));
            commoidty.setPrice(rs.getDouble(3));
            commoidty.setAgio(rs.getDouble(4));
            commoidtyList.add(commodity);
      }
    } finally {
            DBConnection.close(pstmt);
            DBConnection.close(conn);
    }    
     return commodityList;
 }

 public Commodity findCommodityById(int commodityId) {
   Connection conn=DBConnection.getConnection();
   String updateSQL="Select * from commodity where commodityId=?";
   PreparedStatement pstmt=null;
   Commodity commodity=new Commodity();
   try {
      pstmt=conn.prepareStatement(updateSQL);
      pstmt.setInt(1.commodityID);
      ResultSet rs=pstmt.executeQuery();
      if (rs.next()) {
            commoidty.setCommodityId(rs.getInt(1));
            commoidty.setCommodityName(rs.getString(2));
            commoidty.setPrice(rs.getDouble(3));
            commoidty.setAgio(rs.getDouble(4));
      }
    } catch (SQLException e){
           e.printStackTrace();
    } finally {
            DBConnection.close(pstmt);
            DBConnection.close(conn);
    }    
     return commodityList;
 }
}


4. DAO Factory.java

package com.ProjectName.factory; 
import com.projectName.dao.CommodityDAO;
import com.projectName.dao.CommodityDAOImpt;
public class CommodityDAOFactory {
  public static Commodity DAO getCommodityDAOInstance(){
    return new CommoidtyDAOImp();
  }
}




Connector


\WebRoot\DBConnection.java

package.com.ProjectName.util;
import.java.sql.connection;
import.java.sql.DriverManager;
import.java.sql.PreparedStatement;
import.java.sql.ResultSet;
import.java.sql.SQLException;
public class DBConnection {
  private static final String DBDRIVER="com.mysql.jdbc.Driver";
  private static final String DBURL=""jdbc:mysql://localhost:3306/DataBaseName";
  private static final String DBUSER="root";
  private static final String DBPASSWORD="admin";

  public static Connection getConnection(){
    Connection conn=null;
    try {
      Class.forName(DBDRIVER);
      conn=DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
    } catch (ClassNotFoundException e){
      e.printStackTrace();
    } catch {SQLExpection e}{
      e.printStackTrace();
    }
    return conn;
  }  
 
  public static void close(Connection conn) {
    if(conn != null) {
       try{
             conn.close();
      } catch (SQLException e) {
             e.printTrace();
      }
    }
  }

 
  public static void close(PreparedStatement pstmt) {
    if(pstmt != null) {
       try{
             pstmt.close();
      } catch (SQLException e) {
             e.printTrace();
      }
    }
  }

 
  public static void close(ResultSet rs) {
    if(rs != null) {
       try{
             rs.close();
      } catch (SQLException e) {
             e.printTrace();
      }
    }
  }










java-connector

inf: java Web (book) pg 83


\WebRoot\DBConnection.java

package.com.ProjectName.util;
import.java.sql.connection;
import.java.sql.DriverManager;
import.java.sql.PreparedStatement;
import.java.sql.ResultSet;
import.java.sql.SQLException;
public class DBConnection {
  private static final String DBDRIVER="com.mysql.jdbc.Driver";
  private static final String DBURL=""jdbc:mysql://localhost:3306/DataBaseName";
  private static final String DBUSER="root";
  private static final String DBPASSWORD="admin";

  public static Connection getConnection(){
    Connection conn=null;
    try {
      Class.forName(DBDRIVER);
      conn=DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
    } catch (ClassNotFoundException e){
      e.printStackTrace();
    } catch {SQLExpection e}{  
      e.printStackTrace();
    }
    return conn;
  }    
   
  public static void close(Connection conn) {
    if(conn != null) {
       try{
             conn.close();
      } catch (SQLException e) {
             e.printTrace();
      }
    }
  }

   
  public static void close(PreparedStatement pstmt) {
    if(pstmt != null) {
       try{
             pstmt.close();
      } catch (SQLException e) {
             e.printTrace();
      }
    }
  }

   
  public static void close(ResultSet rs) {
    if(rs != null) {
       try{
             rs.close();
      } catch (SQLException e) {
             e.printTrace();
      }
    }
  }

java-database 5 level (over 10 file ) struts2


(5) View (jsp,structs.xml,*Action.java)
.

  1. WebRoot\bookInput.jsp
    <form action="bookInut.action" method="post">
    <s:actionmessage/>
    <input type = "text" name="bookName">
    <input type = "text" name="bookNo">
    <input type = "text" name="bookPrice">
    <input type = "submit">
    <input type = "reset">
    <a href="showAllBook.action">
  2. src\com\ProjectName\action\BookInputAction.java
    public class BookInutAction extends ActionSupport (
    private String bookName;
    private String bookNo;
    private double bookPrice;
    public String execute() throws Exception {
    Book book=new Book();
    book.setBookName(bookName);
    book.setBookNo(bookNo);
    book.setBookPrice(bookPrice);
    BookService bookService=BookServiceFactory.getBookServiceInstance();
    if (bookService.inputBook(book)){
    this.addActionMessage("Logon Success");
    return SUCESS;
    } else {
    this.addActionMessage("Logon Fail");
    return INPUT;
    }
    }
    )
  3. struts.xml
    <action name ="bookInput" class="com.ProjectName.action.BookInputAction">
    <result name="success">/bookInput.jsp</result>
    <result name="input">/bookInput.jsp</result>
    </action>
  4. src\com\ProjectName\action\ShowAllBookAction.java
    public class ShowAllBookAction extneds ActionSupport {
    public String execute() throws Exception {
    BookService bookService =BookServiceFactory.getBookServiceInstance();
    List<Book> bookList=bookService.showAllBook();
    HttpServletRequest request=ServletActionContext.getRequest();
    request.setAttribute("bookList",bookList);
    return SUCCESS;
    }
    }
  5. struts.xml
    <action name ="showAllBook" class="com.ProjectName.action.ShowAllBookAction">
    <result name="success">/showAllBook.jsp</result>
    </action>
  6. \WebRoot\showAllBook.jsp
    <s:iterator value="#request.bookList" var="book">
    <s:property value="#book.bookId"/>
    <s:property value="#book.bookName"/>
    <s:property value="#book.bookNo"/>
    <s:property value="#book.bookPrice"/>
    </s:iterator>


(4) Logical (*service.java)
.

  1. src\com\ProjectName\service\BookService.java
    public interface BookService {
    public boolean inputBook (Book book);
    public List<Book> showAllBook()
    }
  2. src\com\ProjectName\service\BookServiceImpl.java
    public class BookServiceImpl implements BookService {
    private BookDAO bookDAO=BookDAOFactory.getBookDAOInstance();
    public boolean inputBook(Book book) {
    Book oldBook = bookDAO.findByBookNo(Book.getBookNo());
    if (oldBook != null) {
    return false
    } else {
    bookDAO.saveBook (book);
    return true;
    }
    }
    public List<Book> showAllBook() {
    return bookDAO.findAllbook();
    }
    }
  3. src\com\ProjectName\service\BookServiceFactory.java
    public class BookServiceFactory{
    public static BookService getBookServiceInstance(){
    return new BookServiceImpl();
    }
    }
.
(3) DAO (DAOInterface: save, find, list)
  1. src\com\ProjectName\dao\BookDAO.java
    public interface BookDAO{
    public void saveBook (Book book);
    public Book findByBookNo(String bookNo);
    public List<Book> findAllBook();
    }
  2. src\com\ProjectName\dao\BookDAOImpl.java
    public class BookDAOImpl implements BookDAO {

    public List<Book> findAllBook(){
    Session session=HibernateSessionFactory.getSession();
    String hpl="from Book";
    Query query=session.createQuery(hql);
    List<Book> books=query.list();
    HibernateSessionFactroy.closeSession();
    return books;
    }

    public Book findByBookNo(String bookNo){
    Session session=HibernateSessionFactory.getSession();
    String hpl="from Book as book where book.bookNo=:bookNo";
    Query query=session.createQuery(hql);
    query.setString("bookNo",bookNo);
    List<Book> books=query.list();
    HibernateSessionFactroy.closeSession();
    if(books.size()>0) {
    return books.get(0);
    } else {
    return null;
    }
    }

    public saveBook(Book book) {
    Session session=HibernateSessionFactory.getSession();
    Transaction transaction=session.begin Transaction();
    session.save(book);
    transaction.commit();
    HibernateSessionFactroy.closeSession();
    return books;
    }

    }
  3. src\com\ProjectName\dao\BookDAOFactory.java
    public class BookDAOfactory {
    public static BookDAO getBookDAOInstance() {
    return new BookDAOImpl();
    }
    }



(2) Hibernate (xml,table Class)
.

  1. src\com\ProjectName\po\Book.java
    public class Book {
    private int bookId;
    private String bookName;
    private String booNo;
    private double bookPrice
    }
  2. Book.hbm.xml
    <hibernate-mapping>
    <class name="com.ProjectName.po.Book" table="book">
    <id name="bookid">
    <generator class="identity"></generator>
    </id>
    <jproperty name="bookName"></property>
    <jproperty name="bookNo"></property>
    <jproperty name="bookPrice"></property>
    </hibernate-mapping>


(1) Database (create table)
.

  1. create table book (
    bookid int(11) not null auto_increment,
    bookName varchar(30) default NULL,
    bookNo varchar(30) default NULL,
    bookPrice double(5,2) default NULL,
    PRIMARY KEY (bookId)
    )