/** JDBC 2ed p.28, Sun Microsystems (2000/7) Let's Begin Java Lesson 4 (JAVA PRESS Vol.21, 2001/12) JDBC 最初の一歩 (2002/1/11) Insert a record into Access *.mdb by T.katayama */ import java.sql.*; import java.io.*; // 省略可能 public class JdbcInsertSample { public static void main (String args[]) { String myurl = "jdbc:odbc:FRIENDS"; String myuser = "user01", mypword = "passwd01"; Connection mycon = null; // Type1(JDBC-ODBC Bridge)ドライバの登録 try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException ex) { System.err.println("Error: the JDBC driver is not found!"); ex.printStackTrace(); System.exit(1); } // Database接続(Connectionオブジェクトの取得) try { mycon = DriverManager.getConnection (myurl,myuser,mypword); } catch (SQLException ex) { System.err.println("Error: the DB connection cannot open! "); ex.printStackTrace(); System.exit(1); } // レコードの追加 Statement mystmt = null; try { // SQLコンテナの作成 mystmt = mycon.createStatement(); // SQLの実行 String mysql = "INSERT INTO FRIENDS_DT(NAME,MAIL,NICKNAME) VALUES(" + "'"+args[0] + " " +args[1] + "'," + "'"+args[2] +"'," + "'" + args[3] + "'" +")"; int num = mystmt.executeUpdate(mysql); System.out.println("SQL: " + mysql); System.out.println("追加登録件数: " + num); // オブジェクトの削除 mystmt.close(); } catch(SQLException ex) { System.err.println("Error: the SQL cannot execute! "); ex.printStackTrace(); // SQL実行時エラーの表示 while(ex != null) { System.err.println(ex.getMessage()); System.err.println("SQL state:"+ex.getSQLState()); System.err.println("Erro Code:"+ex.getErrorCode()); System.out.println(""); ex = ex.getNextException(); } } catch(Exception ex) { ex.printStackTrace(); System.out.println("例外エラー:" + ex); // 最後に必ず実行されるブロック } finally { // Database切断 try { mycon.close(); } catch(SQLException ex) { System.err.println("Error : DB close."); ex.printStackTrace(); System.exit(1); } } } // end of main }