不好意思。我在判断是不存在特定的用户时可能用错方法了。
大家帮我看一下这个BEAN,我定义了一个静态变量static int num=0; //用户ID,每次新注册用户,自增1
,目的是为了在注册新用户时,记录用户的ID,
conn=getConnection();
sql=" insert into user values(?,?,?) ";
pstmt=conn.prepareStatement(sql) ;
pstmt.setInt(1,++num) ;
pstmt.setString(2,name);
pstmt.setString(3,password);
pstmt=conn.prepareStatement(sql) ;
pstmt.executeUpdate();
但我在pstmt.setInt(1,++num);时系统报错,说第一参数没有设置,不知我错在哪里?谢谢!
package etrade;
import java.io.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class UserBean implements Serializable {
static int num=0; //用户ID,每次新注册用户,自增1
private String id;
private String name;
private String password;
private DataSource ds=null;
public UserBean() throws NamingException{
Context ctx = new InitialContext() ;
ds = (DataSource) ctx.lookup("java:comp/env/jdbc/etrade") ;
}
public int getNum(){
return num;
}
public String getId(){
return id;
}
public void setId(String id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password=password;
}
public Connection getConnection() throws SQLException{
return ds.getConnection();
}
/**
* 关闭连接对象
*/
protected void closeConnection(Connection conn){
if (conn!=null){
try{
conn.close();
conn=null;
}catch(SQLException ex){
ex.printStackTrace() ;
}
}
}
/**
* 关闭Statement对象
*/
protected void closeStatement(Statement stmt){
if (stmt!=null){
try{
stmt.close();
stmt=null;
}catch(SQLException ex){
ex.printStackTrace() ;
}
}
}
/**
* 关闭PreparedStatement对象
*/
protected void closePreparedStatement(PreparedStatement pstmt){
if (pstmt!=null){
try{
pstmt.close();
pstmt=null;
}catch(SQLException ex){
ex.printStackTrace() ;
}
}
}
/**
* 关闭ResultSet对象
*/
protected void closeResultSet(ResultSet rs){
if (rs!=null){
try{
rs.close();
rs=null;
}catch(SQLException ex){
ex.printStackTrace() ;
}
}
}
/*
*新用户注册
*/
public void registerUser() throws SQLException{
Connection conn=null;
PreparedStatement pstmt=null;
String sql=null;
try{
conn=getConnection();
sql=" insert into user values(?,?,?) ";
pstmt=conn.prepareStatement(sql) ;
pstmt.setInt(1,++num) ;
pstmt.setString(2,name);
pstmt.setString(3,password);
pstmt=conn.prepareStatement(sql) ;
pstmt.executeUpdate();
}finally{
closePreparedStatement(pstmt);
closeConnection(conn);
}
}
}