2013-02-05 35 views
3

我现在开始使用java.sql包,我正在做一些实验。preparedStatement和resultSet接口如何使用批处理和获取方法

我有这两个表

第一个是:

`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`) ,... 

,其中用户ID是相关联的第一个表的用户ID的外键。

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

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(); 

如果我会做这个过程中越来越多的夫妇(用户名,clubname),例如保存在一个HashMap中我如何可以使用addBatch()preparedStatement时Inteface的方法??

我应该使用三批一个用于eache动作: 1插入用户ID 3插入关联到正确的用户ID clubname的用户名 2选择(和记录)的

或者我可以包括在所有的过程只有一批?

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

在此先感谢所有愿意帮助我的人!

回答

2

您不能仅在一个批次中包含所有进程。该批次适用于单个查询。以下是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(仅当它跳转)否则为false。如果resultSet包含多个行,则可以将其放在内,而循环,如果不是只需要使用,条件是那里。