简体   繁体   中英

Removing \n from result of mysql query

I have a table containing a field with data type as varchar, so it can have any type of text including alpha numeric characters and symbols etc. I have to get that text using mysql query in a module made in java and write in a file. In single line text it works fine but the Issue occurs when there are \\n in the text.

ISSUE:

When I get text through query I do not find any \\n in value but when I write in file it is written with line breaks. Later I have to read that file line by line using some other java utility and line breaks disturb my logic.

Example:

Hafiz saleem ullah     
Hamza iron store  
 ( New lari adda Jalal pur bhattian)  
0547 500830  
03006523830  
03229256356

Above text is stored in one field but displayed as mentioned above. There is no \\n visible in the text but actually there are. This is single line text which is divided in multiple lines because of line breaks.

Code to fetch data from DB:

Below are the java code lines to fetch data from DB using stored procedure passed as parameter sqlStmt and to extract value from result.

conn = DatabasePool.poolDs.getConnection();
stmt = conn.createStatement();
rslt = stmt.executeQuery(sqlStmt);
int numcols = rslt.getMetaData().getColumnCount();
while (rslt.next()) {
    String[] row = new String[numcols];
    for (int i = 0; i < numcols; i++) {
    row[i] = rslt.getString(i + 1);
    }
result.add(row);
}

if (result.size() > 0) {
    status = result.get(0)[0]; //toString() is implicit here
}

NOTE: Now data is in status variable which is written in file using log4j library.

String text = <<you db field value>>;

text = text.replace("\n", "");

I guess that besides \\n , the text may contain \\r . After test, the code below may resolve your problem, eg:

String yourResult = "abc\r\n def\r\n\t1234";
yourResult = yourResult.replaceAll("[\\n\\r]", "");

The output will be:

abc def 1234

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM