gpt4 book ai didi

java - 如果其中一个字段可能为空,如何更新表中的多个字段?

转载 作者:可可西里 更新时间:2023-11-01 07:59:36 26 4
gpt4 key购买 nike

我想在名为 Personnel-table 的表中更新用户个人信息的 5 字段。

用户可能想要更新所有字段、部分字段或根本不更新任何字段。

用户可能想要更新的字段是:FirstNameLastNamePasswordUserName地址 .

该代码执行此操作:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com