廣告

2015年2月28日 星期六

[SQL] View

View 

如果在資料庫的應用中,出現很常執行的查詢敘述時, 你可以在MySQL資料庫中建立一種「View」元件,
View元件用來保存一段你指定的查詢敘述:
建立好需要的View元件以後,除了有一些限制外,
它使用起來就像是一個表格 也有很多人稱「View」元件是一種「虛擬表格」,
因為它不是一個真正儲存紀錄資料的表格,
可是它又跟表格的用法類似。
所以如果有需要的話,你也可以使用View元件回傳的紀錄資料,
執行統計、分組與其它需要的處理: 

 下列是MySQL關於View元件的規定與限制: 

在同一個資料庫中,View的名稱不可以重複,也不可以跟表格名稱一樣 View不可以跟Triggers建立聯結 儲存在View中的查詢敘述也有下列的規定: 查詢敘述中只能使用到已存在的表格或View 「FROM」子句中不可以使用子查詢 不可以使用「TEMPORARY」表格 不可以使用自行定義的變數、Procedure與Prepared statement參數 註:「TEMPORARY」表格在「表格與索引、建立表格、建立暫存表格」中討論。「Triggers」、定義變數、「Procedure」與「Prepared statement」在後面都會有章節詳細的討論。
參考來源



新增view
mysql> create view testtable2View as select* from testtable2 order by car;
Query OK, 0 rows affected (0.00 sec)

mysql> select* from testtable2View ;
+----+-------+------+-------+-----+-------+
| id | name  | job  | price | car | title |
+----+-------+------+-------+-----+-------+
|  1 | lewis | sw   | 2     |   2 | NULL  |
|  4 | jim   | sw   | 7     |   6 | NULL  |
|  2 | lewis | sw   | 3     | 111 | NULL  |
|  3 | leo   | sw   | 4     | 123 | NULL  |
+----+-------+------+-------+-----+-------+
4 rows in set (0.00 sec)


修改view
mysql> alter view testtable2View as select* from testtable2 order by price;
Query OK, 0 rows affected (0.00 sec)

mysql> select* from testtable2View ;
+----+-------+------+-------+-----+-------+
| id | name  | job  | price | car | title |
+----+-------+------+-------+-----+-------+
|  1 | lewis | sw   | 2     |   2 | NULL  |
|  2 | lewis | sw   | 3     | 111 | NULL  |
|  3 | leo   | sw   | 4     | 123 | NULL  |
|  4 | jim   | sw   | 7     |   6 | NULL  |
+----+-------+------+-------+-----+-------+
4 rows in set (0.00 sec)


刪除view
mysql> drop view if exists testtable2View;
Query OK, 0 rows affected (0.00 sec)
mysql> select* from testtable2View ;
ERROR 1146 (42S02): Table 'testdb.testtable2View' doesn't exist


檢查view的狀態
check table testtable2View;
注意:不是: check view testtable2View;

select* from information_schema.views;

[SQL] subquery | 子查詢


select, where , from, 等語句都可以內嵌子查詢的語法.
括號裡面的回傳欄位只能是一個
mysql> select* from testtable2 where price  > (select price from testtable2 where name = 'leo' ) ;
+----+------+------+-------+-----+-------+
| id | name | job  | price | car | title |
+----+------+------+-------+-----+-------+
|  4 | jim  | sw   | 7     |   6 | NULL  |
+----+------+------+-------+-----+-------+
1 row in set (0.00 sec)


IN

mysql> select* from testtable2 where name in ('lewis','leo' ) ;                     
+----+-------+------+-------+-----+-------+
| id | name  | job  | price | car | title |
+----+-------+------+-------+-----+-------+
|  1 | lewis | sw   | 2     |   2 | NULL  |
|  2 | lewis | sw   | 3     | 111 | NULL  |
|  3 | leo   | sw   | 4     | 123 | NULL  |
+----+-------+------+-------+-----+-------+
3 rows in set (0.00 sec)

[SQL] Alter table | 修改資料表


修改table 屬性:
mysql> alter table testtable2 CHARSET = utf8;
看修改後的結果:
mysql> show create table testtable2;

| testtable2 | CREATE TABLE `testtable2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(35) CHARACTER SET latin1 NOT NULL,
  `price` char(35) CHARACTER SET latin1 NOT NULL,
  `car` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 |


查看索引資訊:
mysql> show index from testtable2;


增加一個欄位
mysql> alter table testtable2 add job varchar(20) default 'sw'after name;
mysql> select* from testtable2;                             
+----+-------+------+-------+-----+
| id | name  | job  | price | car |
+----+-------+------+-------+-----+
|  1 | lewis | sw   | 2     |   2 |
|  2 | lewis | sw   | 3     | 111 |
|  3 | leo   | sw   | 4     | 123 |
|  4 | jim   | sw   | 7     |   6 |
+----+-------+------+-------+-----+
4 rows in set (0.00 sec)


增加多個欄位
mysql> alter table testtable2 add (job2 varchar(20) , year varchar(20) );
mysql> select* from testtable2;                             
+----+-------+------+-------+-----+------+------+
| id | name  | job  | price | car | job2 | year |
+----+-------+------+-------+-----+------+------+
|  1 | lewis | sw   | 2     |   2 | NULL | NULL |
|  2 | lewis | sw   | 3     | 111 | NULL | NULL |
|  3 | leo   | sw   | 4     | 123 | NULL | NULL |
|  4 | jim   | sw   | 7     |   6 | NULL | NULL |
+----+-------+------+-------+-----+------+------+
4 rows in set (0.00 sec)


修改欄位: 
1.CHANGE 可以修改欄位的名稱與定義.
2.MODIFY 只能修改欄位的定義,不能修改欄位名稱.
 一般來說會覺得change涵蓋兩種功能所以我們用change就好,
MODIFY可以防止不小心改到欄位名的狀況.

CHANGE
mysql> alter table testtable2 change job2 title varchar(30);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select* from testtable2;                             
+----+-------+------+-------+-----+-------+------+
| id | name  | job  | price | car | title | year |
+----+-------+------+-------+-----+-------+------+
|  1 | lewis | sw   | 2     |   2 | NULL  | NULL |
|  2 | lewis | sw   | 3     | 111 | NULL  | NULL |
|  3 | leo   | sw   | 4     | 123 | NULL  | NULL |
|  4 | jim   | sw   | 7     |   6 | NULL  | NULL |
+----+-------+------+-------+-----+-------+------+
4 rows in set (0.00 sec)


MODIFY
mysql> alter table testtable2 modify year int(10) after title;
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select* from testtable2;                            
+----+-------+------+-------+-----+-------+------+
| id | name  | job  | price | car | title | year |
+----+-------+------+-------+-----+-------+------+
|  1 | lewis | sw   | 2     |   2 | NULL  | NULL |
|  2 | lewis | sw   | 3     | 111 | NULL  | NULL |
|  3 | leo   | sw   | 4     | 123 | NULL  | NULL |
|  4 | jim   | sw   | 7     |   6 | NULL  | NULL |
+----+-------+------+-------+-----+-------+------+
4 rows in set (0.00 sec)


刪除其中一個欄位
mysql> alter table testtable2 drop year;
Query OK, 4 rows affected (0.01 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select* from testtable2;
+----+-------+------+-------+-----+-------+
| id | name  | job  | price | car | title |
+----+-------+------+-------+-----+-------+
|  1 | lewis | sw   | 2     |   2 | NULL  |
|  2 | lewis | sw   | 3     | 111 | NULL  |
|  3 | leo   | sw   | 4     | 123 | NULL  |
|  4 | jim   | sw   | 7     |   6 | NULL  |
+----+-------+------+-------+-----+-------+
4 rows in set (0.01 sec)

[Java] Use recursive way to print complex data structure type until primitive data type.

As title , the ALHM(hash map in array list ) or HMAL(arraylist in hash map)
is my favorite data structure ,
but sometime if there are many content in that,
you may not see clearly from your print,
So i provide a simple way so print data clearly.

is also support ALHM(HMAL(ALHM)), nest data structure .

your data may like this:

[
  {
    key1:[item1,item2,.....],
    key2:[item1,item2,.....],
    key3:[item1,item2,.....],
    key4:[item1,item2,.....],
    key5:[item1,item2,.....],
    key6:[item1,item2,.....],
    key7:[item1,item2,.....]
  },
  
  {
    key1:[item1,item2,.....],
    key2:[item1,item2,.....],
    key3:[item1,item2,.....],
    key4:[item1,item2,.....],
    key5:[item1,item2,.....],
    key6:[item1,item2,.....],
    key7:[item1,item2,.....]
  },
  
  {
    key1:[item1,item2,.....],
    key2:[item1,item2,.....],
    key3:[item1,item2,.....],
    key4:[item1,item2,.....],
    key5:[item1,item2,.....],
    key6:[item1,item2,.....],
    key7:[item1,item2,.....]
  },
  
]  

here is code.

ViewDat.java

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.acer.util.DataUtil;


public class ViewDat {

 public boolean viewDat(String fileName) {

  File file = new File(fileName);
  if (file.exists()) {
   Object object = DataUtil.DeSerialization(fileName);
   if (object instanceof Map) {
    System.out.println(fileName + " is Map");
    getMapContent((Map)object);
   } else if (object instanceof List) {
    System.out.println(fileName + " is List");
    getListContent((List)object);
   } else {
    System.out.println(fileName + " only support map and list");
   }
  } else {
   System.out.println(fileName + " is not exist");
  }

  return true;
 }
 
 public void getMapContent(Map map ){
  
  Iterator keyIt = map.keySet().iterator();
     
  while (keyIt.hasNext()) {

   String key = keyIt.next();
   
   Object object = map.get(key);

   if (null!= object && ! DataUtil.isPrimitiveType(object.getClass())) {
    System.out.println("==="+key+"===");
   }
   
   recursive2Primitive(object,key);
  }
 }
 
 public void getListContent(List list){
  
  for(int i = 0 ; i < list.size() ; i ++  ){

   Object object = list.get(i);
   System.out.println("===================");
   recursive2Primitive(object,null);
   
   
  }
  
 }
 
 public void recursive2Primitive(Object object, String key){
  
  if (null != object && object instanceof Map) {

   getMapContent((Map) object);

  } else if (null != object && object instanceof List) {

   getListContent((List) object);

  } else if (null != object && DataUtil.isPrimitiveType(object.getClass())) {

   System.out.println(key+" : "+object.toString());

  } else if(null != object){

   System.out.println("not support this type, content is "
     + object.toString());

  }else{
   System.out.println("=============================== ");
   System.out.println("content is null, can't print ");
   System.out.println("=============================== ");
  }
  
 }

}

2015年2月26日 星期四

[java] Check primitive data type

you can modify this method to what the type you need. at line 45~55
package test_fb_api;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class testCheckPrimitive {

 public static void main(String[] args) {

  java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(".*[^0-9].*");
  
  int a =0 ;
  double id = 0.0;
  String s = "111";
  Double d = 1.0;
  Map map = new HashMap();
  
  asignVar(a);
  asignVar(id);
  asignVar(s);
  asignVar(d);
  asignVar(map);
  
 }

 public static void asignVar(Object obj){
  
  Object o = obj;
  System.out.println(o.getClass());
  System.out.println(isWrapperType(o.getClass()));
  System.out.println("=========================");
  
 }
 private static final Set <Class<?>> WRAPPER_TYPES = getWrapperTypes();
 
  public static boolean isWrapperType(Class<?> clazz)
     {
         return WRAPPER_TYPES.contains(clazz);
     }
  
  private static Set<Class<?>> getWrapperTypes()
     {
         Set<Class<?>> ret = new HashSet<Class<?>>();
         ret.add(Boolean.class);
         ret.add(Character.class);
         ret.add(Byte.class);
         ret.add(Short.class);
         ret.add(Integer.class);
         ret.add(Long.class);
         ret.add(Float.class);
         ret.add(Double.class);
         ret.add(Void.class);
         ret.add(String.class);
         return ret;
     }
  
}

2015年2月24日 星期二

[ubuntu][unfinish] linux grep and , or

http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators/


http://linux.vbird.org/linux_basic/0320bash.php

2015年2月21日 星期六

[SQL] tool of sql

三種sql tool
1.cmd line










2. MySqlWorkbench






















3.Aqua Data Studio

[SQL]在同一個Database內 ,查詢多個表格 || search multi table in one database


在同一個db內 查詢多個表格.

資料表內容如下:





















inner join
語法(3種):但我偏好用第一種.
第一種
 
    mysql> select * from testtable, testtable2 where
    -> testtable.name = testtable2.name;

這種同上,只是這種會幫 表格再取一個別名(把她想成宣告一個變數出來使用)
mysql> select * from testtable a, testtable2 b where a.name = b.name; 










第二種
mysql> select * from testtable inner join testtable2 
on testtable.name = testtable2.name;










第三種
mysql> select * from testtable inner join testtable2 using(name);










有inner join 就會有outer join 但因為我比較少用所以不做介紹

union
其實就是把兩個select 的結果一起show出來:
mysql> select* from testtable where name = 'lewis' 
union select* from testtable2 where name = 'lewis';

2015年2月7日 星期六

[webservice][java] use spring lib to connect mysql x eclipse

上一篇 講到如何用struct2的 framework,
這一篇要講用spring 的lib 來連接mysql ,
會使用到資料庫基本的 新增刪改。

完整專案可於 github 下載,

專案結構如下:


專案所需lib














Install mysql if you don't have it.


看sql可以用打指令的方式或使用以下工具:


















配置web.xml(添加以下資訊)


  DB Connection
  jdbc/admin
  javax.sql.DataSource
  Container
 
 
  DB Connection
  jdbc/testdb
  javax.sql.DataSource
  Container
 
   


配置context.xml

       
 








index.jsp (view)
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   


Hello World


   

Hello World From Struts2

Hello World From Struts2 Extend

Hello World From Struts2 Map

Insert people to testdb

id: name: school: age:

Update people to testdb

id: name: school: age:

Query people by name

Query people by school

Delete all people

Delete people by school



ShowDbResult.jsp
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>


Hello World


  

Select Records:

id: name: school: age


配置struts.xml


   
     
      
            /HelloWorld.jsp
      
      
       
            /HelloWorld.jsp
            /AccessDenied.jsp
         
        
            /HelloWorldMap.jsp
            /AccessDenied.jsp
         
          
            /ShowDbResult.jsp
            /AccessDenied.jsp
         
          
            /ShowDbResult.jsp
            /AccessDenied.jsp
         
          
            /ShowDbResult.jsp
            /AccessDenied.jsp
         
         
            /ShowDbResult.jsp
            /AccessDenied.jsp
         
          
            /ShowDbResult.jsp
            /AccessDenied.jsp
         
          
            /ShowDbResult.jsp
            /AccessDenied.jsp
         
         
      
   
   





新增vo(value object) class, PeopleVo.java
用來對應資料庫用
package com.tutorial.vo;

import java.sql.Timestamp;

public class PeopleVo {
 private int id;
 //need to keep this arg,(spring lib need)
 //but you don't need to set it,
 //because this column is auto gen
 
 private String name;
 private String school;
 private int age;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getSchool() {
  return school;
 }
 public void setSchool(String school) {
  this.school = school;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }

}



新增DAO(data access object) class,用來處理db connect
BaseDao.java and PeopleVo.java
package com.tutorial.dao;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

public abstract class BaseDao {
 public static final String DATA_SOURCE_ADMIN = "java:comp/env/jdbc/admin";
 public static final String DATA_SOURCE_TESTDB = "java:comp/env/jdbc/testdb";

 private static Map dsMap = new HashMap();
 private transient NamedParameterJdbcTemplate namedParameterJdbcTemplate = null;

 private NamedParameterJdbcTemplate getNamedParameterJdbcTemplate(
   DataSource datasource) {
  if (this.namedParameterJdbcTemplate == null) {
   this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(
     datasource);
  }

  return this.namedParameterJdbcTemplate;
 }

 protected DataSource getDataSource(String dsName) {
  synchronized (dsMap) {
   Object obj = dsMap.get(dsName);

   if (obj == null) {
    try {
     final InitialContext initContext = new InitialContext();
     obj = initContext.lookup(dsName);
     dsMap.put(dsName, (javax.sql.DataSource) obj);
    } catch (NamingException e) {
     e.printStackTrace();
    }
   }

   return (javax.sql.DataSource) obj;
  }
 }

 /**
  * 查詢List
  * 
  * @param sql
  * @param bean
  * @param rowMapper
  * @return
  * @throws IOException
  * @throws DataAccessException
  */
 protected  List query(final String dsName, final String sql,
   final Object parameterbean, final RowMapper rowMapper) {
  try {
   return getNamedParameterJdbcTemplate(getDataSource(dsName)).query(
     sql, new BeanPropertySqlParameterSource(parameterbean),
     rowMapper);
  } catch (EmptyResultDataAccessException ex) {
   return null;
  }
 }

 /**
  * 更新資料
  * 
  * @param methodName
  * @param sql
  * @param parameterbean
  * @return
  */
 protected int update(final String dsName, final String sql,
   final Object parameterbean) {
  return getNamedParameterJdbcTemplate(getDataSource(dsName)).update(sql,
    new BeanPropertySqlParameterSource(parameterbean));
 }

 private NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
  if (this.namedParameterJdbcTemplate == null) {
   this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(
     getDataSource(DATA_SOURCE_TESTDB));
  }

  return this.namedParameterJdbcTemplate;
 }

 protected int execute(final String sql, Map paramMap) {
  return getNamedParameterJdbcTemplate().update(sql, paramMap);
 }

 protected KeyHolder execute(final String sql,
   BeanPropertySqlParameterSource paramSource) {
  KeyHolder keyholder = new GeneratedKeyHolder();
  getNamedParameterJdbcTemplate().update(sql, paramSource, keyholder);
  return keyholder;
 }
}


package com.tutorial.impdao;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;

import com.tutorial.dao.BaseDao;
import com.tutorial.vo.PeopleVo;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PeopleDao extends BaseDao {
 private static PeopleDao dao = new PeopleDao();

 public static PeopleDao getInstance() {
  return dao;
 }

 private PeopleDao() {
 }

 private static final String SQL_DELETE = "DELETE " + "FROM " + "testtable ";

 public void delete(final PeopleVo vo) {

  execute(SQL_DELETE, new BeanPropertySqlParameterSource(vo));
 }

 private static final String SQL_DELETE_BY_SCHOOL = "DELETE " + "FROM "
   + "testtable " + "WHERE " + "school = :school";

 public void deleteBySchool(final PeopleVo vo) {

  execute(SQL_DELETE_BY_SCHOOL, new BeanPropertySqlParameterSource(vo));
 }

 private static String SQL_Q_ALL = "SELECT * FROM " + "testtable";

 public List selectALL(final PeopleVo vo) {
  return this.query(DATA_SOURCE_TESTDB, SQL_Q_ALL.toString(), vo,
    BeanPropertyRowMapper.newInstance(PeopleVo.class));
 }

 private static String SQL_Q_Name = "SELECT * FROM " + "testtable"
   + " WHERE name = :name";

 public List selectByName(final PeopleVo vo) {
  return this.query(DATA_SOURCE_TESTDB, SQL_Q_Name.toString(), vo,
    BeanPropertyRowMapper.newInstance(PeopleVo.class));
 }

 private static String SQL_Q_SCHOOL = "SELECT * FROM " + "testtable"
   + " WHERE school = :school";

 public List selectBySchool(final PeopleVo vo) {
  return this.query(DATA_SOURCE_TESTDB, SQL_Q_SCHOOL.toString(), vo,
    BeanPropertyRowMapper.newInstance(PeopleVo.class));
 }

 private static final String SQL_INSERT = "INSERT INTO " + "testtable "
   + "VALUES(:id, :name, :school, :age) ";

 public void insert(final PeopleVo vo) {
  if (vo == null)
   throw new IllegalArgumentException("VO is null!!");

  execute(SQL_INSERT, new BeanPropertySqlParameterSource(vo));
 }

 private static final String SQL_UPDATE_BY_NAME = "UPDATE " + "testtable "
   + "SET school = :school, age = :age " + "WHERE name = :name ";

 public void update(final PeopleVo vo) {
  if (vo == null)
   throw new IllegalArgumentException("VO is null!!");
  System.out.print(vo);

  execute(SQL_UPDATE_BY_NAME, new BeanPropertySqlParameterSource(vo));
 }

}



對應struts的class & method ,HellowMySql.java
package com.tutorialspoint.struts2;

import java.util.ArrayList;
import java.util.List;

import com.tutorial.impdao.PeopleDao;
import com.tutorial.vo.PeopleVo;

public class HellowMySql {
 public int id;
 public String name;
 public String school;
 public int age;
 public ArrayList daoL = new ArrayList();
 
 public String insert() throws Exception {
  PeopleDao dao = PeopleDao.getInstance();
  PeopleVo vo = new PeopleVo();
  //vo.setId(id);
  vo.setName(name);
  vo.setSchool(school);
  vo.setAge(age);
  System.out.println("insert to db: "+id+":"+name+":"+school+":"+age);
  dao.insert(vo);
  
  List daoDB = dao.selectALL(vo);
     for(int i = 0 ; i < daoDB.size() ; i++)
     {
      PeopleVo vod = new PeopleVo();
      vod.setId(daoDB.get(i).getId());  
      vod.setName(daoDB.get(i).getName()); 
      vod.setSchool(daoDB.get(i).getSchool()); 
      vod.setAge(daoDB.get(i).getAge()); 
      
      daoL.add(vod); 
      System.out.println("query from db:"+vod.getName());
     }
  return "success";
 }
 
 public String QueryByName() throws Exception {
  PeopleDao dao = PeopleDao.getInstance();
  PeopleVo vo = new PeopleVo();
  vo.setName(name);
  System.out.println("QueryByName :"+name);
  
  List daoDB = dao.selectByName(vo);
     for(int i = 0 ; i < daoDB.size() ; i++)
     {
      PeopleVo vod = new PeopleVo();
      vod.setId(daoDB.get(i).getId());  
      vod.setName(daoDB.get(i).getName()); 
      vod.setSchool(daoDB.get(i).getSchool()); 
      vod.setAge(daoDB.get(i).getAge()); 
      
      daoL.add(vod); 
      System.out.println("query from db:"+vod.getName());
     }
  return "success";
 }
 
 
 public String QueryBySchool() throws Exception {
  PeopleDao dao = PeopleDao.getInstance();
  PeopleVo vo = new PeopleVo();
  vo.setSchool(school);
  System.out.println("QueryBySchool: "+school);
  
  List daoDB = dao.selectBySchool(vo);
     for(int i = 0 ; i < daoDB.size() ; i++)
     {
      PeopleVo vod = new PeopleVo();
      vod.setId(daoDB.get(i).getId());  
      vod.setName(daoDB.get(i).getName()); 
      vod.setSchool(daoDB.get(i).getSchool()); 
      vod.setAge(daoDB.get(i).getAge()); 
      
      daoL.add(vod); 
      System.out.println("query from db:"+vod.getName());
     }
  return "success";
 }
 
 public String UpdateByName() throws Exception {
  PeopleDao dao = PeopleDao.getInstance();
  PeopleVo vo = new PeopleVo();
  vo.setName(name);
  vo.setSchool(school);
  vo.setAge(age);
  System.out.println("UpdateByName: "+name);
  
  System.out.println("before UpdateByName: "+name);
  
  List daoDB = dao.selectByName(vo);
     for(int i = 0 ; i < daoDB.size() ; i++)
     {
      PeopleVo vod = new PeopleVo();
      vod.setId(daoDB.get(i).getId());  
      vod.setName(daoDB.get(i).getName()); 
      vod.setSchool(daoDB.get(i).getSchool()); 
      vod.setAge(daoDB.get(i).getAge()); 
      
      daoL.add(vod); 
     }
  
  dao.update(vo);
  
  List daoDBa = dao.selectByName(vo);
     for(int i = 0 ; i < daoDB.size() ; i++)
     {
      PeopleVo vod = new PeopleVo();
      vod.setId(daoDBa.get(i).getId());  
      vod.setName(daoDBa.get(i).getName()); 
      vod.setSchool(daoDBa.get(i).getSchool()); 
      vod.setAge(daoDBa.get(i).getAge()); 
      
      daoL.add(vod); 
     }
  return "success";
 }
 
 public String DeleteAll() throws Exception {
  PeopleDao dao = PeopleDao.getInstance();
  PeopleVo vo = new PeopleVo();
  System.out.println("DeleteAll");
  
  dao.delete(vo);
  
  List daoDB = dao.selectALL(vo);
     for(int i = 0 ; i < daoDB.size() ; i++)
     {
      PeopleVo vod = new PeopleVo();
      vod.setId(daoDB.get(i).getId());  
      vod.setName(daoDB.get(i).getName()); 
      vod.setSchool(daoDB.get(i).getSchool()); 
      vod.setAge(daoDB.get(i).getAge()); 
      
      daoL.add(vod); 
      System.out.println("query from db:"+vod.getName());
     }
  return "success";
 }
 
 public String DeleteBySchool() throws Exception {
  PeopleDao dao = PeopleDao.getInstance();
  PeopleVo vo = new PeopleVo();
  System.out.println("DeleteBySchool :"+ school);
  vo.setSchool(school);
  dao.deleteBySchool(vo);
  
  List daoDB = dao.selectALL(vo);
     for(int i = 0 ; i < daoDB.size() ; i++)
     {
      PeopleVo vod = new PeopleVo();
      vod.setId(daoDB.get(i).getId());  
      vod.setName(daoDB.get(i).getName()); 
      vod.setSchool(daoDB.get(i).getSchool()); 
      vod.setAge(daoDB.get(i).getAge()); 
      
      daoL.add(vod); 
      System.out.println("query from db:"+vod.getName());
     }
  return "success";
 }
 
 
 public ArrayList getDaoList() {  
     return daoL;  
 }  
 public void setDaoList(ArrayList daoL) {  
     this.daoL = daoL;  
 } 

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  System.out.println("call getName");
  return name;
 }

 public void setName(String name) {
  System.out.println("call setName");
  this.name = name;
 }
 public String getSchool() {
  return school;
 }

 public void setSchool(String school) {
  this.school = school;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }


}


主畫面:















結果畫面:


2015年2月4日 星期三

[SQL] install mysql on ubuntu and start it. | create, insert , delete , update ,

sudo apt-get install mysql-server-5.5
/etc/mysql$ vim my.cnf
如果需要讓MySQL從遠端連進來的話,把 bind_address 這個參數從 127.0.0.1 改成主機的實體 IP 位址。
$ sudo service mysql start
sudo /etc/init.d/mysql start

進入mysql
 mysql -u root -p

change the password of root to "lewis"
GRANT ALL PRIVILEGES ON *.* TO root@localhost IDENTIFIED BY "lewis";

create database testdb;

create accoount: "lewis" , password:"lewis"
GRANT ALL PRIVILEGES ON testdb.* TO lewis@localhost IDENTIFIED BY "lewis" with grant option;

查看該使用者有無權限:
SHOW GRANTS FOR lewis@localhost;

use testdb;
create table testtable 
( id int not null auto_increment primary key, 
name char(35) not null, school char(35) not null, 
age int(11) not null);

發現用aqua一值連不到我vm的sql,最後發現是 權限問題,真是....
 sudo chmod -R 755 /var/lib/mysql/
這樣就可以了.



show出目前有的database
 SHOW DATABASES;

使用哪個db
  use testdb;

show出這個db裡面有哪些table
   show tables;

show出這個table裡面的內容 (select)
 select * from testtable;

新增一筆資料到table
 insert into testtable (name,school,age) values('jim','acer','35');

insert into testtable (name,school) values('jim','acer');


更新一筆資料到 table
 update testtable set age = '30' where name = 'leo'; 


刪除資料
 delete from testtable where age > '1111';

刪除table中所有資料
 truncate from testtable ;


名詞解釋:
索引:

primary key:一個表格只能有一個。
在一個表格中,設定為主索引鍵的欄位值不可以重複,且不可以儲存「NULL」值。
適合使用在類似編碼、代號或身份證字號這類欄位。

unique index(不可重複索引):表格中,設定為唯一索引的欄位值不可以重複,但是可以儲存「NULL」值。這種索引適合用在類似員工資料表格中儲存電子郵件帳號的欄位,因為員工不一定有電子郵件帳號,所以允許儲存「NULL」值,每一個員工的電子郵件帳號都不可以重複。

non-unique index:只是用來增加查詢與維護資料效率的索引。設定為非唯一索引的欄位值可以重複,也可以儲存「NULL」值。


ref:
http://www.codedata.com.tw/database/mysql-tutorial-getting-started
http://www.1keydata.com/sql/alter-table-drop-constraint.html

續:lampp 

ref:http://www.rackspace.com/knowledge_center/article/installing-mysql-server-on-ubuntu
補充: 這種安裝法會在/etc/init.d, 會註冊到service.
開機順序在etc/rc, s=start,k = stop,
mount point 要先起來,如果有其他要用到.
系統有需要的都要close/open.

2015年2月3日 星期二

[java] image base64 encode and decode

package image.process;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class imageCode64 {

 
 
 
    /**
     * Decode string to image
     * @param imageString The string to decode
     * @return decoded image
     */
    public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * Encode image to string
     * @param image The image to encode
     * @param type jpeg, bmp, ...
     * @return encoded string
     */
    public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            
            
            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

 
}

[ubuntu] 備份檔案,並傳送到其他主機. | tar, scp , tar

目的:
將測試機的A檔案傳到正式機的A檔案.

 1.備份測試機and正式機的A檔案.(tar) $ tar zcv -f FileName.tar.gz DirName

 2.將測試機的A檔案傳到正式機的A檔案 (scp) $ scp Run.sh    
    acer@xxx.xxx.xxx.xxx:~/opt/cronjobs/eInvoice/

 3.在正式區解開此A檔案(tar) $ tar zxv -f FileName.tar.gz
    || $ tar zxv -f FileName.tar.gz -C your path -z  .
 
    透過 gzip進行壓縮/解壓縮,檔名為 *.tar.gz -c .
    -c : 建立打包檔案
    -x :解打包或解壓縮  .
    -v : 在壓縮/解壓縮的過程中,將正在處理的檔名顯示出來 -f filename:
    -f 後面要立刻接要被處理的檔名 -p(小寫) :
    保留備份資料的原本權限與屬性,常用於備份(-c)重要的設定檔 -P(大寫) :
    保留絕對路徑,亦即允許備份資料中含有根目錄存在之意;
    (不建議大寫P) 因為在 tar 所記錄的檔名就是解壓縮後的實際檔名。
   如果拿掉了根目錄, 假設你將備份資料在/tmp 解開,那麼解壓縮的
   檔名就會變成/tmp/etc/xxx,如果沒有拿掉根目錄, 解壓縮後的檔名就
   會是絕對路徑, 亦即解壓縮後的資料一定會被放置到 /etc/xxx 去,
   如此一來, 你的原本的 /etc/ 底下的資料, 就會被備份資料所
   覆蓋 PS: rm -rf /root/etc /tmp/etc 務必要確認一下後面接的檔名. 如果
   我們要刪除的是 /root/etc 與 /tmp/etc, 可不要將 /etc/ 刪除掉了

[java][webService] struts2 action

網頁端程式上使用action:
  action="../payment/Pay.auth.do
  (..為出去2層的意思)

struts.xml的設定:
 
  
   /payment/result.jsp
   /epay/migs/auth.jsp
  
 


 解釋:
      第一個{1} = Pay 所以:
      class="com.acer.epay.action.PayAction"
      第一個{2} = auth 所以:
      method = auth() //會去呼叫class裡面的auth().
   
      兩個result可以把他們想成case switch.
      根據auth()回傳去執行哪個 xxx.jsp.

2015年2月2日 星期一

[java] soap client sample code






package soapClient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.soap.*;
//http://stackoverflow.com/questions/15948927/working-soap-client-example
//http://harryjoy.com/2011/10/20/soap-client-in-java/
//http://cafeconleche.org/books/xmljava/chapters/ch03s05.html
//maven http://www.logicsector.com/java/how-to-create-a-wsdl-first-soap-client-in-java-with-cxf-and-maven/
public class SOAPClientSAAJ {

 
 //  http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx?wsdl
  
    public static void main(String args[]) throws Exception {
        // Create SOAP Connection
        SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection soapConnection = soapConnectionFactory.createConnection();
        
        // Send SOAP Message to SOAP Server
        String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
        SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);

        // print SOAP Response
        System.out.println("Response SOAP Message:");
        
        //save response string
        File file = new File("soapClient.txt");
        FileOutputStream fop = new FileOutputStream(file);
        if (!file.exists()) {
   file.createNewFile();
  }
        
        soapResponse.writeTo(fop);
        soapResponse.writeTo(System.out);
        soapConnection.close();
    }

    private static SOAPMessage createSOAPRequest() throws Exception {
        MessageFactory messageFactory = MessageFactory.newInstance();
        SOAPMessage soapMessage = messageFactory.createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();

        String serverURI = "http://ws.cdyne.com/";

        // SOAP Envelope
        SOAPEnvelope envelope = soapPart.getEnvelope();
        envelope.addNamespaceDeclaration("example", serverURI);

        /*example
        Constructed SOAP Request Message:
        
            
            
                
                    mutantninja@gmail.com
                    123
                
            
        
         */

        // SOAP Body
        SOAPBody soapBody = envelope.getBody();
        SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
        SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
        soapBodyElem1.addTextNode("mutantninja@gmail.com");
        SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
        soapBodyElem2.addTextNode("123");

        MimeHeaders headers = soapMessage.getMimeHeaders();
        headers.addHeader("SOAPAction", serverURI  + "VerifyEmail");

        soapMessage.saveChanges();

        /* Print the request message */
        System.out.println("Request SOAP Message:");
        soapMessage.writeTo(System.out);
        System.out.println("getXmlFromSOAPMessage============");
        //get request string
        System.out.println(getXmlFromSOAPMessage(soapMessage));

        return soapMessage;
    }
    
    static String getXmlFromSOAPMessage(SOAPMessage msg) throws SOAPException, IOException {
        ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
        msg.writeTo(byteArrayOS);
        return new String(byteArrayOS.toByteArray());
    }
}


















ref:http://w3school.com.cn/soap/soap_header.asp

[java][webservice] structs2 x eclipse x window8

前言1:java , tomcat設定 可以參考.前面幾篇
前言2:struts2 架構


Struts 2 Architecture


Struts2 的 Action 能夠相容 POJO
講白話一點就是什麼都不用繼承的 class 就能當 Action 用.
POJO類別簡單來說,就是單純的
Java類別,不帶有其他框架 API 呼叫,開發者可以以簡單不複雜的方式(不必實
作一些繁複的介面或繼承)來開發商業邏輯,減少與其他元件的耦合性.
action:Each URL is mapped to a specific action.

專案結構:





2. create dynamic web project






















3. put structs2 lib to your web-inf\lib














4. create model =>HelloWorldAction.java  
Struts 2 framework will create an object of HelloWorldAction.java,
and call execute method.

package com.tutorialspoint.struts2;

public class HelloWorldAction{
   private String name;
   private String age;

 public String getAge() {
  return age;
 }

 public void setAge(String age) {
  this.age = age;
 }

 public String execute() throws Exception {
  System.out.println(name+age);
  return "success2";
 }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}


5. create view    under webContent=>HelloWorld.jsp
<s:property value="name"/> 會呼叫 HelloWorldAction.java的getname()

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>Hello World
</head>
<body>
   Hello World,<s:property value="name">
   

   age ,<s:property value="age">
</body>
</html>

6.create main page   under webContent => index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
   
<html>
<head>
Hello World
</head>
<body>
   

Hello World From Struts2

Hello World From Struts2 Extend

Hello World From Struts2 Map

</body> </html>

action = hello . mapping to HelloWorldAction class , use struts.xml to setting





7.create struts.xml under src/


   
     
      
            /HelloWorld.jsp
      
      
       
            /HelloWorld.jsp
            /AccessDenied.jsp
         
        
            /HelloWorldMap.jsp
            /AccessDenied.jsp
         
      
   
   









The only requirement for actions in Struts2 is that there must be one no-argument method that returns either a String or Result object and must be a POJO. If the no-argument method is not specified, the default behavior is to use the execute() method.



8.create web.xml  under webContent/web-inf

   
   Struts 2
   
      index.jsp
   
   
      struts2
      
         org.apache.struts2.dispatcher.FilterDispatcher
      
   

   
      struts2
      /*
 
 
   





9.enable detail log (先跳過)





10. [test] run your project 












11. struts.properties file (if need, this will have default)

### When set to true, Struts will act much more friendly for developers
struts.devMode = true

### Enables reloading of internationalization files
struts.i18n.reload = true

### Enables reloading of XML configuration files
struts.configuration.xml.reload = true

### Sets the port that the server is run on
struts.url.http.port = 8080

      create under web-inf/classes




Create Multiple Actions


_1.  create HelloWorldActionExtendActionSupport.java

package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldActionExtendActionSupport extends ActionSupport{
   private String name;

   public String execute() throws Exception {
      if ("SECRET".equals(name))
      {
         return SUCCESS;
      }else{
         return ERROR;  
      }
   }
   
   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}


_2.  add content to struts.xml



   
     
      
            /HelloWorld.jsp
      
      
       
            /HelloWorld.jsp
            /AccessDenied.jsp
         
        
            /HelloWorldMap.jsp
            /AccessDenied.jsp
         
      
   
   













ValueStack/OGNL Example


The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion.


=1.  create HelloWorldActionExtendActionMap.java

package com.tutorialspoint.struts2;

import java.util.*; 

import com.opensymphony.xwork2.util.ValueStack;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class HelloWorldActionMap extends ActionSupport{
   private String name;

   public String execute() throws Exception {
      ValueStack stack = ActionContext.getContext().getValueStack();
      Map context = new HashMap();

      context.put("key1", this.name); 
      context.put("key2", this.name);
      stack.push(context);

      System.out.println("Size of the valueStack: " + stack.size());
      return "success";
   }  

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

=2. add content to struts.xml(同上)
=3. add HolloWorldMap.jsp

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
Hello World
</head>
<body>
   Entered value : <s:property value="name">

   Value of key 1 : <s:property value="key1">

   Value of key 2 : <s:property value="key2"> 


</body>
</html>








2015年2月1日 星期日

[java] split string by dot | 用 dot 來切割字串

package test_fb_api;

import java.util.Arrays;

public class testStringSplite {

 public static void main(String[] args) {

  String locat = "http://ibobar-content.oss-cn-hangzhou.aliyuncs.com/book1669/hj1669_ipad.png";
  String[] temp = locat.split("/");
  String downloadPath = "ibobar" + "/" + "getBookList"
    + "/" + temp[temp.length - 2] + ".jpg";
  
  System.out.println("method 1:");
  String ss = temp[temp.length - 1];
  String[] temp2 = ss.split("\\.");
  System.out.println("副檔名 = "+temp2[temp2.length - 1]);
  //System.out.println(Arrays.toString(temp2));
  System.out.println("===============================");
  
  System.out.println("method 2:");
  int startIndex = ss.lastIndexOf(46) + 1;
  int endIndex = ss.length();
  System.out.println("副檔名 = " + ss.substring(startIndex, endIndex)); // 副檔名
  
 }

}