a ridi a ridi - 1 month ago 5
Java Question

SQL, JAVA Remove Duplicate Strings from SQL output, Array Sort

I'm accessing an SQL database and I want to retrieve all serial numbers in a column, my problem is not here, my problem is that the sql statement brings all serial numbers whether its duplicate or not.

Here is my SQL Statement;

String sqlS = "Select (SerialNumber) from dbo.Results where ErrorCode != 0 AND LineNumber = 1 AND TMDT BETWEEN '" +ourJavaDateObject + "' AND '" + tomorrow + "'";


Here is the output:

16110201009
16110201014
16110201017
16110201048
16110201048
16110201048
16110201048
16110201048
16110201048


Please notice that there are 6 of the same serial number, how can I sort that to delete the serial number.

This is the output that I would like:

16110201009
16110201014
16110201017
16110201048

Answer

To get unique values you need to use the keyword DISTINCT.

String sqlS = "SELECT DISTINCT (SerialNumber) FROM dbo.Results WHERE ErrorCode != 0 AND LineNumber = 1 AND TMDT BETWEEN '" +ourJavaDateObject + "' AND '" + tomorrow + "'";

However your code is not safe against SQL injection, because you parse arguments directly. Would you think of using PreparedStatement?