3

私は今パッケージjava.sqlを使い始めており、それを使っていくつかの実験を行っています。

私はこれらの2つのテーブルを持っています

最初は:

`user` (
`userID` INT NOT NULL AUTO_INCREMENT ,
`nickname` VARCHAR(20) NULL ,
PRIMARY KEY (`userID`) )

そして2番目は:

`club` (
`clubID` INT NOT NULL AUTO_INCREMENT ,
'clubName` VARCHAR(20) NOT NULL ,
`userID` INT NULL , 
PRIMARY KEY (`clubID`) ,...

ここで、userIDは、最初のテーブルのuserIDに関連付けられた外部キーです。

そして、これは私がやりたいことを説明するコードです。(これは1つのユーザークラブ専用です)

Class.forName("com.mysql.jdbc.Driver");
this.connect = DriverManager.getConnection("jdbc:mysql://localhost/" + this.database + "?user=" + this.user + "&password=" + this.password);
String s;

s = ("insert into " + this.database + ".user (nickname) values (?)");
this.preparedStatement = this.connect.prepareStatement(s);
this.preparedStatement.setString(1, "username");
this.preparedStatement.executeUpdate();

s = ("SELECT userID from " + this.database + ".user where nickname = 'username'");
this.preparedStatement = this.connect.prepareStatement(s);
this.resultSet = this.preparedStatement.executeQuery();
int n=0;
while (resultSet.next())
{
    n = this.resultSet.getInt("userID");
}

s = ("insert into " + this.database + ".club (clubName, userID) values (?, ?)");
this.preparedStatement = this.connect.prepareStatement(s);
this.preparedStatement.setString(1, "club");
this.preparedStatement.setInt(2, n);
this.preparedStatement.executeUpdate();

たとえばHashMapに保存されている、より多くのカップル(ユーザー名、クラブ名)に対してこのプロセスを実行する場合、preparedStatement IntefaceのaddBatch()メソッドをどのように使用できますか?

アクションごとに1つずつ3つのバッチを使用する必要があります。1ユーザー名の挿入2ユーザーIDの選択(および記録)3正しいユーザーIDに関連付けられたクラブ名の挿入

または、すべてのプロセスを1つのバッチに含めることができますか?

そして別の質問、resultSet.getInt()メソッドを囲むwhileサイクルを削除しようとすると、エラーが発生するのはなぜですか?

私を助けようとするすべての人に事前に感謝します!

4

1 に答える 1

2

すべてのプロセスを1つのバッチに含めることはできません。バッチは単一のクエリを対象としています。これが良い例のリファレンスリンクです。

次のように、複数のクエリを異なるバッチとして実行できます。

    try {
        DataSource dataSource = null;// specify data source
        Connection con = dataSource.getConnection();
        Statement s = con.createStatement();
        // or
        // PreparedStatement s =
        // con.prepareStatement("INSERT INTO profile (fullname) VALUES ('Visruth CV')");
        s.addBatch("INSERT INTO tran1 (username, password, profileid) VALUES ('visruth', 'password', 1)");
        s.addBatch("INSERT INTO testtab (name) VALUES ('testtab')");
        s.executeBatch();

    } catch (SQLException e) {
        e.printStackTrace();
    }

while (resultSet.next())ループを削除すると、カーソルの現在の位置がデフォルトの行にあるため、 NullPointerExceptionが発生します。作成すると、使用可能な行がある場合はカーソルが次の行にジャンプします(デフォルトの行から最初の行、最初の行から2番目の行など)、同時にtrue(ジャンプする場合のみ)を返し、それ以外の場合はfalseを返します。複数の行が含まれている場合、if条件を使用する必要がない場合は、whileループ内に配置できますresultSetresultSet.next()resultSet.next()resultSet

于 2013-02-06T11:16:57.677 に答える