Java とデータベース

Java には、データベース用のクラスが用意されています。ただし、使用するには個々のデータベース用に、ドライバを入手する必要があります。ドライバについては、それぞれのデータベースのマニュアルをご参照ください。

ここでは、PreparedStatementクラスを用いる方式を説明します。

データベースへのアクセスを確保する


データベースへアクセスするには、まずDriverManagerクラスでドライバを指定します。

        Connection connection;
        Statement statement;
	String driver = "com.mysql.jdbc.Driver";
	String openDBString = "jdbc:mysql://localhost/";
	String user = "easai";
	String password = "password";
	String dbName = "dictionaries";
	try
	    {
		Class.forName(driver).newInstance(); 		
		connection = DriverManager.getConnection(openDBString+dbName,user,password);
		statement = connection.createStatement();
	    }
	catch(Exception e){e.printStackTrace();}

データを保存する


アクセスが確保されれば、SQL文を用意します。

PreparedStatementを使うと、Unicodeを含む文字列でも自由に値を設定できます。

  1. SQL文を設定し、バイナリで指定したい値を、? で置き換えます。
  2. PreparedStatement.setBytes()メソッドで、順に値を代入します。
  3. PreparedStatement.executeUpdate() メソッドなどで、SQL文を実行します。

	try
	    {
		String tableName = "french";
		String usage = "les raz-de-marée du 26 décembre";
		String word = "raz-de-marée";
		String description = "tsunami";

		String sql = "INSERT INTO "+tableName+" VALUES(?,?,?);";
		PreparedStatement preparedStatement = connection.prepareStatement(sql);
		preparedStatement.setBytes(1,usage.getBytes("UTF8"));
		preparedStatement.setBytes(2,word.getBytes("UTF8"));
		preparedStatement.setBytes(3,description.getBytes("UTF8"));
		if(preparedStatement.executeUpdate() == -1)
		    JOptionPane.showMessageDialog(this,"The database can not execute the following SQL command: \n"+sql);
	    }
	catch(Exception e){e.printStackTrace();}

データベースを閉じる


データベースへを閉じるには、Connectionや Statementクラスのオブジェクトをclose()メソッドで閉じます。

	try 
	    { 
		if(statement != null) 
		    statement.close(); 
		if(connection != null) 
		    connection.close(); 
	    } 
	catch (Exception e){e.printStackTrace();}
inserted by FC2 system