Solaris10からSQL Server 2000 (JDBC)
の続きです。
runSQLメソッドを以下のように変更します。
public void runSql() {
Connection con = getConnection();
if (con != null) {
try {
PreparedStatement ps =
con.prepareStatement("SELECT * FROM 住所録 WHERE id = ?");
ps.setInt(1, 1);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String contactName = rs.getString("名前");
System.out.println(contactName);
}
rs.close();
ps.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
closeConnection(con);
}
}
}
ちなみに、見に行くのは「住所録」という日本語名のテーブルの、「名前」
というフィールド。id = 1には「たにぐち」と入っています。
結果は
接続成功!
たにぐち
と無事に出力されました。どうやら日本語は大丈夫のようですね。
以下プロファイラの出力です。PreparedStatementのパラメータが
どのように処理されているか!?
select @@MAX_PRECISION
declare @P1 int
set @P1=180150000
declare @P2 int
set @P2=4
declare @P3 int
set @P3=1
declare @P4 int
set @P4=-1
exec sp_cursoropen @P1 output, N'SELECT * FROM 住所録 WHERE id = @P1', @P2 output, @P3 output, @P4 output, N'@P1 int ', 1
select @P1, @P2, @P3, @P4
exec sp_cursorfetch 180150000, 2, 1, 256
exec sp_cursorfetch 180150000, 2, 1, 256
exec sp_cursorclose 180150000
API システム ストアド プロシージャを使用しています。
このプロシージャは直接の呼出はサポートしていないそうです(なのでBooks Onlineにも
使用方法は書かれていません)。
ADO、OLE DB、ODBC、および DB-Library などから呼ばれると書いてありますが、
JDBC Driverもこの中に入るようです。
詳しくはBooks Online参照。
ここで、Visual Basic 6.0の登場。ADOをつかいDSNで接続。
Private Sub Command1_Click()
Dim adoCon As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
adoCon.ConnectionString = _
"DSN=********;DATABASE=xxxxxx;UID=sa;PWD=********"
adoCon.Open
With cmd
.ActiveConnection = adoCon
.CommandText = "SELECT * FROM 住所録 WHERE id = ?"
.CreateParameter , adInteger, adParamInput
.Parameters(0).Value = 1
End With
Set rs = cmd.Execute
Do Until rs.EOF
Debug.Print rs.Fields("名前").Value
rs.MoveNext
Loop
rs.Close
adoCon.Close
End Sub
プロファイラの結果は
declare @P1 int
set @P1=1
exec sp_prepare @P1 output, N'@P1 int', N'SELECT * FROM 住所録 WHERE id = @P1', 1
select @P1
同様にAPI システム ストアド プロシージャを使っていますが、別なストアド(sp_prepare)を使っています。
ADO.NETの場合は、確かsp_executesql。これならBooks Onlineに使い方が載っています。
ううん、同じことをしているはずなのに色々ですね。
それにしてもSolaris版(motif)Eclipseちょっと重いです。仕事で使うにはちょっとツラそう。