作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我想在名为 Personnel-table
的表中更新用户个人信息的 5
字段。
用户可能想要更新所有字段、部分字段或根本不更新任何字段。
用户可能想要更新的字段是:FirstName
、LastName
、Password
、UserName
和地址
.
该代码执行此操作:
public boolean updateUserInfo(String _idnumber , String _usernameNew , String _passwordNew ,
String _addressNew , String _firstNameNew , String _lastNameNew) throws SQLException
{
ResultSet resultSet = null;
String sqlStatement = "UPDATE PersonnelTable set `UserName` = ? WHERE `IdNumber` = ?";
this.m_prepared = (PreparedStatement) this.m_connection.prepareStatement(sqlStatement);
this.m_prepared.executeUpdate("USE Personnel");
// set the ID number & account number
/**
* first
*/
m_prepared.setString(1, _usernameNew);
m_prepared.setString(2, _idnumber);
// execute first query - update password
if (_usernameNew!= "")
{
resultSet = m_prepared.executeQuery();
return true;
}
/**
* Second
*/
sqlStatement = "UPDATE PersonnelTable set `FirstName` = ? WHERE `IdNumber` = ?";
this.m_prepared = (PreparedStatement) this.m_connection.prepareStatement(sqlStatement);
m_prepared.setString(1, _firstNameNew);
m_prepared.setString(2, _idnumber);
if (_firstNameNew != "")
{
resultSet = m_prepared.executeQuery();
return true;
}
/**
* Third
*/
sqlStatement = "UPDATE PersonnelTable set `LastName` = ? WHERE `IdNumber` = ?";
this.m_prepared = (PreparedStatement) this.m_connection.prepareStatement(sqlStatement);
m_prepared.setString(1, _lastNameNew);
m_prepared.setString(2, _idnumber);
if (_lastNameNew!= "")
{
resultSet = m_prepared.executeQuery();
return true;
}
/**
* Fourth
*/
sqlStatement = "UPDATE PersonnelTable set `Address` = ? WHERE `IdNumber` = ?";
this.m_prepared = (PreparedStatement) this.m_connection.prepareStatement(sqlStatement);
m_prepared.setString(1, _addressNew);
m_prepared.setString(2, _idnumber);
if (_addressNew!= "")
{
resultSet = m_prepared.executeQuery();
return true;
}
/**
* Fifth
*/
sqlStatement = "UPDATE PersonnelTable set `Password` = ? WHERE `IdNumber` = ?";
this.m_prepared = (PreparedStatement) this.m_connection.prepareStatement(sqlStatement);
m_prepared.setString(1, _passwordNew);
m_prepared.setString(2, _idnumber);
if (_passwordNew!= "")
{
resultSet = m_prepared.executeQuery();
return true;
}
return false;
}
但如您所见,代码太大,因为我运行了 5 次查询。
如何告诉 mysql 如果每个字段都不是空字符串 ""
,然后更新需要的字段,在一个 mysql 查询中?这是可能的还是我必须每次都单独做?
问候
最佳答案
您可以在单个查询中轻松地执行此操作:
UPDATE PersonnelTable
SET FirstName = IF(? <> "", ?, FirstName),
LastName = IF(? <> "", ?, LastName),
Password = IF(? <> "", ?, Password),
UserName = IF(? <> "", ?, UserName),
Address = IF(? <> "", ?, Address)
WHERE IdNumber = ?;
如果您的字段可以有空白值,例如 ""
,那么您可以使用 IF(? IS NOT NULL, ?, field_name)
而不是空白。
关于java - 如果其中一个字段可能为空,如何更新表中的多个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11896238/
我是一名优秀的程序员,十分优秀!