我有一种方法来检查数据库中是否存在记录。 如果记录在数据库中,它应该返回false,但是如果它不存在则应该插入记录并返回true。
当前状态下的代码似乎工作正常但是如果记录没有在需要的时候将新行插入数据库,我似乎无法理解为什么会这样。
public boolean createRecord(Myuser myuser)
{
Connection cnnct = null;
PreparedStatement pStmnt = null;
try
{
cnnct = getConnection();
String preQueryStatement = "SELECT * FROM MYUSER WHERE MYUSER.USERID = ?";
pStmnt = cnnct.prepareStatement(preQueryStatement);
pStmnt.setString(1,myuser.getUserid());
ResultSet rs = pStmnt.executeQuery();
if (!rs.next())
{
String insertStatement
= "INSERT INTO MYUSER VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
pStmnt = cnnct.prepareStatement(insertStatement);
pStmnt.setString(1, myuser.getUserid());
pStmnt.setString(2, myuser.getName());
pStmnt.setString(3, myuser.getPassword());
pStmnt.setString(4, myuser.getEmail());
pStmnt.setString(5, myuser.getPhone());
pStmnt.setString(6, myuser.getAddress());
pStmnt.setString(7, myuser.getSecQn());
pStmnt.setString(8, myuser.getSecAns());
pStmnt.executeUpdate();
System.out.println("new user inserted");
return true;
}
else
{
System.out.println("user already in data base");
return false;
}
}
catch (SQLException ex)
{
while (ex != null)
{
ex.printStackTrace();
ex = ex.getNextException();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
if (pStmnt != null)
{
try
{
pStmnt.close();
}
catch (SQLException e)
{
}
}
if (cnnct!= null)
{
try
{
cnnct.close();
}
catch (SQLException sqlEx)
{
}
}
}
}
答案 0 :(得分:1)
ResultSet rs = pStmnt.executeQuery()将返回永远不会为null的结果集,直到没有异常,如果你想检查是否有记录,你可以使用rs.next()方法验证是否有任何记录存在或不在结果集
public boolean createRecord(Myuser myuser)
{
Connection cnnct = null;
PreparedStatement pStmnt = null;
try
{
cnnct = getConnection();
String preQueryStatement
= "SELECT * FROM MYUSER WHERE MYUSER.USERID = ?;";
pStmnt = cnnct.prepareStatement(preQueryStatement);
pStmnt.setLong(1,youruserid);
ResultSet rs = pStmnt.executeQuery();
if (!rs.next())
{
String insertStatement
= "INSERT INTO MYUSER VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement ps = cnnct.prepareStatement(insertStatement);
ps.setString(1, myuser.getUserid());
ps.setString(2, myuser.getName());
ps.setString(3, myuser.getPassword());
ps.setString(4, myuser.getEmail());
ps.setString(5, myuser.getPhone());
ps.setString(6, myuser.getAddress());
ps.setString(7, myuser.getSecQn());
ps.setString(8, myuser.getSecAns());
System.out.println("new user inserted");
return true;
}
else
{
System.out.println("user already in data base");
return false;
}
}
catch (SQLException ex)
{
while (ex != null)
{
ex.printStackTrace();
ex = ex.getNextException();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
if (pStmnt != null)
{
try
{
pStmnt.close();
}
catch (SQLException e)
{
}
}
if (cnnct!= null)
{
try
{
cnnct.close();
}
catch (SQLException sqlEx)
{
}
}
}
}