【问题标题】:preparedStatement and resultSet interfaces how to use batch and get methodsPreparedStatement和resultSet接口如何使用batch和get方法
【发布时间】:2013-01-21 01:41:00
【问题描述】:

我现在开始使用 java.sql 包,我正在用它做一些实验。

我有这两张桌子

第一个是:

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

第二个是:

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

其中 userID 是与第一个表的 userID 关联的外键。

这是应该解释我想要做什么的代码。 (这仅适用于一个用户俱乐部)

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 接口的addBatch() 方法??

我应该为每个动作使用三批: 1 插入用户名 2 userID的选择(和记录) 3 插入与正确用户 ID 关联的俱乐部名称

或者我可以只在一个批次中包含所有过程??

还有一个问题,为什么如果我尝试删除围绕 resultSet.getInt() 方法的 while 循环,它会给我一个错误??

提前感谢所有愿意帮助我的人!

【问题讨论】:

    标签: java mysql batch-file prepared-statement resultset


    【解决方案1】:

    您不能只在一个批次中包含所有流程。该批处理旨在用于单个查询。这是reference link 的一个很好的例子。

    您可以按如下方式按不同批次执行多个查询。

        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,因为resultSet 中的光标当前位置在默认行中,当您将resultSet.next() 设置为光标时如果有可用行(从默认行到第一行,第一行到第二行等),将跳转到下一行,同时resultSet.next() 将返回 true(仅当它跳转时)否则错误的。如果resultSet包含多于一行,可以放在一个while循环中,如果不只需要使用if条件那里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 2015-06-07
      相关资源
      最近更新 更多