javaその4(DBアクセス)
さらに続き。
データベースアクセスを試す。
色々忘れている。流石に忘れている。
Class.forNameとか懐かしすぐる。
まあ、いい。
繋いだのはpostgres。
jdbcはmacportsでサクッと入れた。
で、まずeclipseでクラスパスを通す。
eclipseではビルドパスから設定するみたい。
なぜ、クラスパスではなく、ビルドパスなのか疑問に思いつつ、postgresのjdbcがどこに入っているのか調べる。
/opt/local/share/java/
にあるpostgresql.jarを追加。
でつないでみる。
当然繋がらない。
tcpipでつながってくれないみたい。
Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections
だってさ。
なんだかんだいじったけど結局は
/opt/local/var/db/postgresql84/defaultdb/postgresql.conf
の#listen_addresses = 'localhost'をコメントアウトしたらいけた。
confの位置がmacportsで入れるか、他の手段で入れるかで場所が変わるからその辺り探すのが面倒。
ただ、バージョンアップをセコセコ自分でしたくないからできる限りはmacportsを使いたい。
で、eclipse上でjdbcの設定して以下のコードで動いた。
package test1; import java.sql.*; public class Cls4 { public void test() throws ClassNotFoundException, SQLException{ Class.forName("org.postgresql.Driver"); Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/xxx","xxx","xxx"); PreparedStatement ps = con.prepareStatement("select * from test0"); ResultSet rs = ps.executeQuery(); while(rs.next()){ int id = rs.getInt(1); String str = rs.getString(2); boolean b = rs.getBoolean(3); System.out.println(String.format("%d,%s,%b", id,str,b)); } } }
繋がらねー、とconfをいじりまわしてたんだけど結局はポート番号を間違えていたという情けないオチだった。
動いたからいいや。
それからResultSetのgetXXXの添字はなんで1スタートなんだろう?0じゃねえのかよ、と思ったのはナイショだ。