事前定義文の利用

/****************************/
/* 事前定義文の利用         */
/*      coded by Y.Suganuma */
/****************************/
import java.io.*;
import java.sql.*;

public class Test {

	public static void main(String args[]) {

		int i1;
		boolean s;
		ResultSet result;
		Connection Con;
					// JDBCドライバの登録
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		}
		catch (Exception e1) {
			System.out.println("Driver Error: " + e1.toString());
		}

		try {
					// データベースへの接続
			Con = DriverManager.getConnection("jdbc:mysql://cs-www/base?" + 
                  "useUnicode=true&characterEncoding=sjis", "xxxxx", "*****");
			try {
						// SQL の実行
				Statement SQL = Con.createStatement();
							// テーブルにデータを追加(ファイル test2.txt から)
				SQL.execute("LOAD DATA LOCAL INFILE \"test2.txt\" INTO TABLE gakuseki");

				SQL.execute("SELECT * FROM gakuseki");
				result = SQL.getResultSet();
				System.out.println("No, name, math");
				while (result.next()) {
					System.out.print("     ");
					for (i1 = 1; i1 <= 3; i1++) {
						if (i1 < 3)
							System.out.print(result.getString(i1) + ", ");
						else
							System.out.print(result.getString(i1));
					}
					System.out.println();
				}
						// SQLを閉じる
		        SQL.close();
						// 事前定義文の利用
				String cmd = "SELECT * FROM gakuseki WHERE name = ? or math >= ?";
				PreparedStatement p_SQL = Con.prepareStatement(cmd);
				p_SQL.setString(1, "鈴木");   // 1番目の?を「鈴木」で置き換える
				p_SQL.setInt(2, 30);   // 2番目の?を「30」で置き換える
				result = p_SQL.executeQuery();
				System.out.println("No, name, math");
				while (result.next()) {
					System.out.print("     ");
					for (i1 = 1; i1 <= 3; i1++) {
						if (i1 < 3)
							System.out.print(result.getString(i1) + ", ");
						else
							System.out.print(result.getString(i1));
					}
					System.out.println();
				}
						// p_SQLを閉じる
		        p_SQL.close();
					// 接続を閉じる
				Con.close();
			}
			catch (SQLException e2) {
				System.out.println("SQL Error: " + e2.toString());
			}
		}
		catch (SQLException e3) {
			System.out.println("SQLException: " + e3.getMessage()); 
			System.out.println("SQLState: " + e3.getSQLState()); 
			System.out.println("VendorError: " + e3.getErrorCode()); 
		}
	}
}