Going my way

いいなと思ったことをメモしていきます。

JavaからMySQLにSELECT文を投げるコードサンプル


Advertisements


MySQLサーバからJavaでデータを取得するためのサンプルを載せます。

まずはDBの情報。
以下のようなDBのデータをJavaを使って取得したい。

mysql> desc test1;
+----------+--------------+------+-----+---------+----------------+
| Field    | Type         | Null | Key | Default | Extra          |
+----------+--------------+------+-----+---------+----------------+
| id       | int(11)      | NO   | PRI | NULL    | auto_increment |
| title    | varchar(100) | YES  |     | NULL    |                |
| author   | varchar(100) | YES  |     | NULL    |                |
| sentence | text         | YES  |     | NULL    |                |
+----------+--------------+------+-----+---------+----------------+
4 rows in set (0.03 sec)

中に入れるデータはこの通り。

insert into test1 values(1,'ONE PIECE','尾田栄一郎','海賊王に おれはなる!');
insert into test1 values(2,'HUNTER HUNTER','冨樫義博','カイトは生きてる!');
insert into test1 values(3,'ドラゴンボール','鳥山明','オラわくわくすっぞ!');

中を見てみよう。

mysql> select * from test1;
+----+----------------+------------+------------------------+
| id | title          | author     | sentence               |
+----+----------------+------------+------------------------+
|  1 | ONE PIECE      | 尾田栄一郎 | 海賊王に おれはなる! |
|  2 | HUNTER HUNTER  | 冨樫義博   | カイトは生きてる!     |
|  3 | ドラゴンボール | 鳥山明     | オラわくわくすっぞ!   |
+----+----------------+------------+------------------------+
3 rows in set (0.00 sec)

参考にしたのは下記のサイトだ。
http://dev.mysql.com/doc/refman/5.1/ja/connector-j-usagenotes-basic.html

properties.txt

jdbc=mysql
host=localhost
db=db1
user=test1
pass=test1
sql=select * from test1

MySQLSelect.java

package jdbc;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.sql.*;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class MySQLSelect {
	private static String jdbc = null;
	private static String db = null;
	private static String host = null;
	private static String user = null;
	private static String pass = null;
	private static String driver = null;
	private static String sql = null;
	
	
	public static void main(String[] args){
		Properties prop = new Properties();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream("properties.txt");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.err.println("プロパティファイルが見つかりません");
		}
		
		try {
			prop.load(fis);
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("プロパティファイルを開けません");
		}
		
		//プロパティの読み込み
		jdbc = prop.getProperty("jdbc");
		db = prop.getProperty("db");
		host = prop.getProperty("host");
		user = prop.getProperty("user");
		pass = prop.getProperty("pass");
		sql = prop.getProperty("sql");
		
		//ドライバの作成
		//jdbc:mysql://localhost/db1?user=test1&password=test1
		driver = "jdbc:"+jdbc+"://"+host+"/"+db+"?user="+user+"&"+"password="+pass;
		
		Connection con = null;
		try{
			con = (Connection) DriverManager.getConnection(driver);
			Statement stmt = (Statement) con.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while(rs.next()){
				int id = rs.getInt("id");
				String title = rs.getString("title");
				String author = rs.getString("author");
				String sentence = rs.getString("sentence");
				System.out.println(id+":【"+ title +"】\n" + author + "\n"+ sentence+"\n");
			}
		}catch(SQLException ex){
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		}finally{
			if(con != null){
				try{
					con.close();
				}catch(SQLException e){
					e.printStackTrace();
				}
			}
		}
		
	}
}

実行すると変なエラーが出たので、修正を試みる。

SQLException: Access denied for user 'test1'@'localhost' (using password: YES)
SQLState: 28000
VendorError: 1045

以下の2つのサイトを参考に、パスワードや権限を再設定した。

http://blog.layer8.sh/ja/2011/12/21/%E3%80%8Cerror-1045-connect-failed-access-denied-for-userusing-password-yes%E3%80%8D%E3%81%AE%E5%AF%BE%E5%87%A6%E6%B3%95symfony/

http://sasuke.main.jp/useri.html

GRANT ALL PRIVILEGES ON *.* TO 'test1'@'localhost' IDENTIFIED BY 'test1'
or
GRANT ALL PRIVILEGES ON *.* TO 'test1'@'%' IDENTIFIED BY 'test1';

無事に実行ができるようになった。<実行結果>

1:【ONE PIECE】
尾田栄一郎
海賊王に おれはなる!

2:【HUNTER HUNTER】
冨樫義博
カイトは生きてる!

3:【ドラゴンボール】
鳥山明
オラわくわくすっぞ!