![](/img/trans.png)
[英]How to compare two MimeMessage.java objects to make sure they are the same?
[英]How to compare VARCHAR data types using Java code to make sure the data is the same in the database
由於數據遷移,如何將兩個不同數據庫中的值與列中的相同數據進行比較。 我正在運行jUnit測試,並且值未通過相同的測試。 我究竟做錯了什么? 知道我將sourceDB和目標數據庫設置為同一數據庫,即它們是同一件事。 我這樣做是因為我想確保連接在整個過程中都是正確的,並將所有問題縮小到語法錯誤。 名稱列各行中的值為: 計划管理,錯誤和增強功能,硬件和軟件請求。
public class DemandTypeCopier {
public static String QUERY_CREATECOPY = "select name from tr_demandtype where name=?";
}
public void testQUERY_CREATECOPY() throws Exception{
UnitTestHelper helper = new UnitTestHelper();
Connection con = helper.getConnection(helper.sourceDBUrl);
Connection conTarget = helper.getConnection(helper.targetDBUrl);
String x = "Initiative management";
PreparedStatement stmt = con.prepareStatement(DemandTypeCopier.QUERY_CREATECOPY);
stmt.setString(1, x);
ResultSet sourceVal = stmt.executeQuery();
stmt = conTarget.prepareStatement(DemandTypeCopier.QUERY_CREATECOPY);
stmt.setString(1, x);
ResultSet targetVal = stmt.executeQuery();
assertTrue(helper.resultSetsEqual(sourceVal,targetVal));
}
public boolean resultSetsEqual (ResultSet source, ResultSet target) throws SQLException{
while(source.next())
{
target.next();
ResultSetMetaData metadata = source.getMetaData();
int count = metadata.getColumnCount();
for (int i =1; i<=count; i++)
{
if(source.getObject(i) != target.getObject(i))
{
return false;
}
}
}
return true;
}
問題在於,在比較數據時,您正在測試對象身份而不是相等性。
source.getObject(i) != target.getObject(i)
上面的代碼將測試從兩個結果集中返回的對象是否相同 ,這在大多數(全部?)情況下都是不正確的。 您真正想做的是測試是否相等:
source.getObject(i).equals(target.getObject(i))
請注意,如果source.getObject(i)返回null,則以上內容將引發NullPointerException,因此,除非數據庫中的任何列均不允許使用null值,否則需要添加代碼以處理null值。
在查詢中添加ORDER BY子句,否則不能保證返回結果的順序。
檢查target.next()的結果,以便當兩個結果集的大小不相等時正確處理這種情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.