我现在开始使用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()方法,它给了我一个错误?
在此先感谢所有愿意帮助我的人!