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.");
    }
  }
}

沒有留言:

張貼留言