PHP字串長度找子字串與取代字串的常用函數

PHP在字串的操作上,有非常多的相關函數可以使用,我們在這裡只介紹經常會使用到的字串操作函數。像是如何取得字串的長度、在某一個字裏面尋找子字串首次出現的位置、以及字串的取代函數...等等。這些都是在編寫程式的時候,頻繁被程式設計師使用到的基礎函數。 取得字串長度 <?...

2012年6月28日 星期四

一個可以將DB table記錄轉換為Java List集合記錄的方法


如何透過JDBC到MySQL資料庫取得PreparedStatement的ResultSet的結果集,並且將每一筆結果集記錄逐一的轉存為List型態的資料集合,我們提供一個DBHelper類別的getDataModel的方法,它主要的作用就是要把ResultSet轉換為TreeMap,最後再把它一一的存到List集合裏面。

獲取Data Model的方法 (DBHelper.getDataModel)

將從資料庫獲取來的PreparedStatement物件導引至getDataModel函式,然後經由函式內部的邏輯處理之後,返回放置TreeMap型態的List集合物件

package jcode.test.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class DBHelper {
  
  public DBHelper(){  }

  public static List<TreeMap> getDataModel(PreparedStatement ps)

 throws SQLException {
    List rst = new ArrayList();
    try {
      ResultSet rs = ps.executeQuery();      
      while(rs.next()){
        ResultSetMetaData rsmd = rs.getMetaData();
        TreeMap map = processResultSet(rsmd, rs);
        rst.add(map);        
      }

    catch (SQLException se) {
      rst = null;
      throw se;
    }
    return rst;
  }

  private static TreeMap processResultSet(ResultSetMetaData rsmd,

 ResultSet rsthrows SQLException {
    TreeMap tmp = new TreeMap();
    try {
      for (int i = 1; i <= rsmd.getColumnCount(); i++) {
        String columnName = rsmd.getColumnName(i).toUpperCase();
        if (rsmd.getColumnType(i== || 

rsmd.getColumnType(i== 12) {
          if (rs.getString(i== null) {
            tmp.put(columnName, "");
          else {
            tmp.put(columnName, rs.getString(i));
          }
        else if (rsmd.getColumnType(i== 93
            || rsmd.getColumnType(i== java.sql.Types.DATE) {
          tmp.put(columnName, rs.getTimestamp(i));
        else if (rsmd.getColumnType(i== java.sql.Types.CLOB) {
          if (rs.getClob(i!= null) {
            tmp.put(columnName,rs.getClob(i).getSubString(1,

 (intrs.getClob(i).length()));
          else {
            tmp.put(columnName, "");
          }
        else {
          tmp.put(columnName, rs.getBigDecimal(i));
        }
      }

    catch (SQLException sex) {
      tmp = null;
      throw sex;
    }
    return tmp;
  }

}

DBTest測試代碼

  • 以JDBC連結到MySQL的test schema
  • 輸入查詢SQL "select * from test.user_info",返回 PreparedStatement型態的ps物件
  • 把ps物件引入到DBHelper.getDataModel方法中,回傳List<TreeMap>型態的list物件
  • 最後產出"總記錄數: XXX"的訊息到畫面上
package jcode.test.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.TreeMap;

public class DBTest {

  /**
   @param args
   */
  public static void main(String[] args) {
    
    Connection con = null;
    try{
      Class.forName("com.mysql.jdbc.Driver");       
      con = DriverManager.getConnection("jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=Big5");
      String sql = "select * from test.user_info;";
      PreparedStatement ps = con.prepareStatement(sql);
      
      List<TreeMap> list = DBHelper.getDataModel(ps);
      if(list != null){
        System.out.println("總筆數: "+list.size());
      }    
    
    }catch(ClassNotFoundException cfe){
      cfe.printStackTrace();
    }catch(SQLException se){
      se.printStackTrace();
    }finally{
      try{
        if(con != nullcon.close();
      }catch(SQLException ignore){  }      
    }
  }

}




2012年6月23日 星期六

Java Calendar取得年(year)、月(month)、日(day)


package com.wen.util;

import java.util.Calendar;

public class DateUtil {
  public static Calendar calendar = Calendar.getInstance();
  
  /**
   * 取得今年年份
   @return
   */
  public static int getThisYear() {    
    return calendar.get(Calendar.YEAR);
  }
  
  /**
   * 取得當月月份
   @return
   */
  public static int getThisMonth() {    
    return calendar.get(Calendar.MONTH1;  
  }
  
  /**
   * 取得今天日期 
   @return
   */
  public static int getThisDay() {    
    return calendar.get(Calendar.DAY_OF_MONTH);
  }
  
  public static void main(String args[]){
    System.out.println("Year="+DateUtil.getThisYear());
    System.out.println("Month="+DateUtil.getThisMonth());
    System.out.println("Day="+DateUtil.getThisDay());    
  }

}

2012年6月22日 星期五

移動滑鼠改變Html表格顏色(change table background on MouseOver)


在此我們簡單的介紹如何利用html,css與js文檔,來實現移動滑鼠(mouseOver或mourseOut)改變表格列的顏色之效果(change table row color on mouseOver or mouseOut),接下來分別說明DEMO畫面CSS代碼(showTbl.css)JS檔案代碼 (chgRowsBg.js)index.htm網頁結果輸出頁面。

DEMO畫面

在瀏灠器上執行index.htm頁面,所產出的結果畫面顯示截圖

移動滑鼠(mouseOver or mouseOut)變換表格列顏色的DEMO畫面


CSS代碼 (showTbl.css)

負責控制Html標籤屬性的呈現效果,例如文字顏色、表格框線、宽度、高度之類的屬性值設定

table.show, table.show td{
    font:73% Arial, Helvetica, sans-serif;
}
table.show {
    width:100%;
    border-collapse:collapse;
}
table.show th, table.show td{
    text-align:left;
    padding:.5em;
    border:1px solid #fff;
    text-align: center;
}
table.show th{
    background:#2F79B8 url(s3-bg.jpg) repeat-x;
    color:#fff;text-align: center;
}
.empty{
    font-size:100%;
} 
table.show tr.even td{
    background:#f9fbfd;
}
table.show tr.odd td{
    background:#e4e4e4;
}
tr.overCss td{
    background:#ffffa2;
}

JS檔案代碼 (chgRowsBg.js)

在瀏灠器載入index.htm頁面之後,負責動態操控改變Html元素的屬性值,讓該元素在輸出端達到變換效果的目的

this.alterTableRowsColor = function() {
    var preCss;
   
 this.start = function(){
     var tables = document.getElementsByTagName('table');
      for(var i=0; i < tables.length; i++){ 
          var tid = tables[i].getAttribute('id');
          if(tid.indexOf("form") != -1)
            showRow(tables[i]);
      }
  };
   
 this.showRow = function(table){
        var trs = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (var i = 0; i < trs.length; i++) {
      trs[i].onmouseover = function(){ over(this); };
      trs[i].onmouseout = function(){ out(this,preCss); };
    }
  };

  this.over = function(obj) {
    preCss = obj.className;
    obj.className = 'overCss';
  };

  this.out = function(obj,preCss){
     //alert("preCss=="+preCss);
    obj.className = preCss;
  };
    
    start();
      
}; 

//window.onload = alterTableRowsColor;               
                         


index.htm頁面程式代碼

一個單純的使用Html表格的標籤撘配CSS與JavaScript文檔所組合而成的Html程式代碼

<html>
<head>
  <link rel="stylesheet" type="text/css" href="showTbl.css" />
  <script type="text/javascript" src="chgRowsBg.js"></script>
</head>
<body onload="alterTableRowsColor();">

<form name="form1" id="form1">
 <table border=0 width="100%">
    <tr>
     <td>
        <table id="form1:table1" border="0" cellpadding="0" cellspacing="0" width="100%" class="show">
            <THead>
                <tr>           
                    <th>Title1</th>
                    <th>Title2</th>
                    <th>Title3</th>
                    <th>Title4</th>
                </tr>      
            </THead>
          <TBody>
            <tr class="even">
              <td>aaa1</td>
              <td>aaa2</td>
              <td>aaa3</td>
              <td>aaa4</td>
            </tr>  
            <tr class="odd">
              <td>bbb1</td>
              <td>bbb2</td>
              <td>bbb3</td>
              <td>bbb4</td>
            </tr>
            <tr class="even">
              <td>ccc1</td>
              <td>ccc2</td> 
              <td>ccc3</td>
              <td>ccc4</td>    
            </tr>
            <tr class="odd">
              <td>ddd1</td>
              <td>ddd2</td>
              <td>ddd3</td>
              <td>ddd4</td>
            </tr>
            <tr class="even">
              <td>eee1</td>
              <td>eee2</td> 
              <td>eee3</td>
              <td>eee4</td>    
            </tr>
          </TBody>
        </table>
   </td>
  </tr>
 </table>
 </form>

</body>
</html>

2012年6月21日 星期四

Java IO讀取(read)、寫入(write)與拷貝(copy)檔案


/**
   * Java IO讀取檔案 (
java io read file)
   @param fileName
   @return
   @throws IOException
   */
  public static List<String> readFile(String fileNamethrows IOException {    
    List<String> rst = new ArrayList<String>();
    BufferedReader br = null;
    try{
      br = new BufferedReader(new FileReader(fileName));
      String in = null;
      while((in = br.readLine()) != null){
        rst.add(in);
      }
    }catch(IOException ioe){
      throw ioe;
    }finally{
      br.close();      
    }    
    return rst;
  }  
  
  /**
    Java IO寫入檔案  (java io write file)
   @param data
   @param fileName
   @throws IOException
   */
  public static void writeFile(List<String> data, String fileNamethrows IOException {
    BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
    try{
      for(String d:data){
        bw.write(d);
        bw.newLine();        
      }
      bw.flush();
    }catch(IOException ioe){
      throw ioe;
    }finally{
      bw.close();      
    }    
  }
  
  /**
    Java IO拷貝檔案 
(java io copy file)
   @param source
   @param dest
   @throws IOException
   */
  public static void copyFile(File source, File destthrows IOException {
    InputStream fis = null;
    OutputStream fos = null;    
    try{
      fos = new FileOutputStream(dest);
      fis = new FileInputStream(source);
      byte[] b = new byte[1024];
      int off = 0;
      int len = 0;
      while((len = fis.read(b)) != -1){
        fos.write(b,off,len);        
      }
      fos.flush();
    }catch(IOException ioe){
      throw ioe;
    }finally{
      fos.close();
      fis.close();
    }
  }