insert 2 lines in a single coloumn cell - java

Can any one suggest how to insert two lines in a single cell? I.e., I need to enter the first line and then the second line should start from new line in the single column cell. Suppose I have a column defined as varchar(100), I need to store the string core java,j2EE will service request as,
core java
j2EE will service request
in a single colomn.
When I retrieve back from the database and displayed on a JSP page it should display in two lines.
I am trying to retrieve Japanese content from database and display using jsp. Is Japanese content (which is in utf-8 format)causing any the problem so that <br /> tag is not parsing as line break.It is coming as string <br /> when I display it on screen.

A newline character ('\n')is still a character, so there's no problem inserting it:
Connection conn = ...;
PreparedStatement ps =
conn.prepareStatement
("INSERT INTO my_table VALUES (?)");
ps.setString (1, "j2EE will service request\nin a single coloumn.");
ps.executeUpdate();
Notes:
Different platforms have different line separators, so depending on how exactly this data is going to be consumed, using System.getProperty("line.separator") may be more appropriate.
For clarity's sake, again, this code omits resource management (e.g., closing the statement) and error-handling code.

Related

Handling word with comma in between in CSV file for input to LOAD DATA LOCAL INFILE

I am working on a java application which inserts data from a CSV file to mysql database table using below query
LOAD DATA LOCAL INFILE 'test.csv' INTO TABLE Test FIELDS TERMINATED BY ',' LINES TERMINATED BY ', ' IGNORE 1 LINES (id, name, address)
I have a issue when there is a comma between words for the a field like for address = pune, india. It is pushing the word after comma to next column.
I have found some workaround, such as escaping comma in Java code like
strAddress = strAddressWithComma.replaceAll(",", "\\"+"\\,");
This works but after data is inserted in DB table it looks like “pune, india” (double quotes around the original string)
Another workaround is adding ENCLOSED BY ‘\”’ clause in LOAD DATA LOCAL INFILE and using below java code.
strAddress ="\"" + strAddressWithComma+ "\"";
But with this workaround also we have string with double quotes around the original string in DB when we use LOAD DATA LOCAL INFILE.
I do not need double quotes around original value in DB after
insertion with Load Data statement . DB entry should be same as that
of data in original csv file.
I know we may have a DB trigger which can strip double quotes from the new string but we want to handle this is application only.
Any solution or suggestion will be appreciated

Removing a /.br/ from a String in Java

I have a Java app that reads data from an Oracle database and then moves it to a MySQL database for research purposes. The data comes from an application where end users can basically enter free text. It appears that when the text is entered they are hitting returns that is causing a /.br/ to appear in the text. MySQL doesn't like the /.br/. I have tried several ways to remove the /.br/ with no luck
clinDisp = clinDisp.replaceAll("<.br */>", "");
clinDisp = clinDisp.replace("/.br/", "");
clinDisp = clinDisp.replace("<.br>", "");
No matter what I try the .br is always there and the insert for this row breaks. Also, if it matters I don't care if the line feed is lost, just something that will allow the String to insert.

Text that contains the apostroph php

I have a serious problem. My app retrieves text from an online database, the problem is that if I put a text in the database that contains the apostrophe in the site displays correctly in the application fails me while synchronizing with the database. I also enabled the magic quote gpc but nothing. How can I fix?
First, disable magic_quote_gpc, as the are deprecated/removed
Secondly, look at mysqli_real_escape_string() when sending data to database (which I assumed is your 'synchronizing with the database' is).
You have to escape the apostroph like this:
INSERT INTO my_table (col1, col2) VALUES (123, 'Hello there''s');
use $user_input = mysql_real_esape_string($user_input)

Fragmented rows in firebird embedded mode

I was doing this code, and something weird has happened.
I make a bulk insert from an external file. But the result it's just fragmented, or maybe corrupted.
cnx=factoryInstace.getConnection();
pstmt = cnx.prepareStatement("DELETE FROM TEMPCELULAR");
pstmt.executeUpdate();
pstmt = cnx.prepareStatement("EXECUTE BLOCK AS BEGIN if (exists(select 1 from rdb$relations where rdb$relation_name = 'EXT_TAB')) then execute statement 'DROP TABLE EXT_TAB;'; END");
pstmt.executeUpdate();
pstmt = cnx.prepareStatement("CREATE TABLE EXT_TAB EXTERNAL '"+txtarchivoProcesar.getText()+"'(CELULAR varchar(11))");
pstmt.executeUpdate();
pstmt = cnx.prepareStatement("INSERT INTO TEMPCELULAR (CELULAR)SELECT CELULAR FROM EXT_TAB");
pstmt.executeUpdate();
pstmt = cnx.prepareStatement("SELECT CELULAR FROM TEMPCELULAR");
ResultSet rs=pstmt.executeQuery();
while(rs.next()){
System.out.println("::"+rs.getString(1));
}
And now, all of a sudden the rows on my table look like this:
::c#gmail.com
::abc2#gmail.
::m
abc3#gma
::.com
abc4#
::ail.com
ab
::#gmail.com
::bc6#gmail.c
::abc7#gmai
::com
abc8#g
::il.com
abc
::gmail.com
::c10#gmail.c
::
The blank spaces between results were not made by me. This is the result as it is.
Source file for external table:
abc#gmail.com
abc2#gmail.com
abc3#gmail.com
abc4#gmail.com
abc5#gmail.com
abc6#gmail.com
abc7#gmail.com
abc8#gmail.com
abc9#gmail.com
abc10#gmail.com
sneciosup#hotmail.com
¿What's wrong with my code?
I've haven't seen this wack results in years.
The database is created of the users pc on the first run. Hence, while in production every time I run the program.
Any help, will be appreciated.
The external table file in Firebird is not just a plaintext file, it is a fixed width format with special requirements to the content and layout. See the Interbase 6.0 Data Definition Guide, page 107-111 (available for download from http://www.firebirdsql.org/en/reference-manuals/ ) or The Firebird Book by Helen Borrie page 281-287.
The problems I see right now are:
you declare the column in the external table to be VARCHAR(11),
while the shortest emailaddress in your file is 13 characters, the
longest is 21 characters, so Firebird will never be able to read a
full emailaddress from the file
you don't specify a separate column for your linebreaks, so your
linebreaks will simply be part of the data which is read
you have declared the column as VARCHAR, this requires the records
to have a very specific format, where the first two bytes declare
the actual data length followed by a string of that length (and even then it
only reads upto the declared length of the column). Either make sure
you follow the requirements for VARCHAR columns, or simply use the
CHAR datatype and make sure you pad the column with spaces upto the
declared length.
I am not 100% sure, but your default database characterset may also be involved in how the data is read.

mssql handles line returns rather awkwardly

Here is the problem:
for your reference:
database entries 1,2 and 3 are made using jython 2.2.1 using jdbc1.2.
database entry 4 is made using vb the old to be replace program using odbc.
We have found that if I copy and paste both jython and vb MailBody entries to wordpad directly from that SQL Server Enterprise Manager software it outputs the format perfectly with correct line returns. if I compare the bytes of each file with a hex editor or KDiff3 they are binary identically the same.
There is a 3rd party program which consumes this data. Sadly that 3rd party program reads the data and for entries 1 to 3 it displays the data without line returns. though for entry 4 it correctly formats the text. As futher proof we can see in the picture, the data in the database is displayed differently.
Somehow the line returns are preserved in the database for the vb entries but the jython entries they are overlooked. if I click on the 'MailBody' field of entry 4 i can press down i can see the rest of the email. Whereas the data for jython is displayed in one row.
What gives, what am i missing, and how do I handle this?
Here is a snippet of the code where I actually send it to the database.
EDIT: FYI: please disregard the discrepancies in the 'Processed' column, it is irrelevant.
EDIT: what i want to do is make the jython program input the data in the same way as the vb program. So that the 3rd party program will come along and correctly display the data.
so what it will look like is every entry in 'MailBody' will display "This is a testing only!" then next line "etc etc" so if I was to do a screendump all entries would resemble database entry 4.
SOLVED
add _force_CRLF to the mix:
def _force_CRLF(self, data):
'''Make sure data uses CRLF for line termination.
Nicked the regex from smtplib.quotedata. '''
print data
newdata = re.sub(r'(?:\r\n|\n|\r(?!\n))', "\r\n", data)
print newdata
return newdata
def _execute_insert(self):
try:
self._stmt=self._con.prepareStatement(\
"INSERT INTO EmailHdr (EntryID, MailSubject, MailFrom, MailTo, MailReceive, MailSent, AttachNo, MailBody)\
VALUES (?, ?, ?, ?, ?, ?, ?, cast(? as varchar (" + str(BODY_FIELD_DATABASE) + ")))")
self._stmt.setString(1,self._emailEntryId)
self._stmt.setString(2,self._subject)
self._stmt.setString(3,self._fromWho)
self._stmt.setString(4,self._toWho)
self._stmt.setString(5,self._format_date(self._emailRecv))
self._stmt.setString(6,self._format_date(self._emailSent))
self._stmt.setString(7,str(self._attachmentCount))
self._stmt.setString(8,self._force_CRLF(self._format_email_body()))
self._stmt.execute()
self._prepare_inserting_attachment_data()
self._insert_attachment_data()
except:
raise
def _format_email_body(self):
if not self._emailBody:
return "could not extract email body"
if len(self._emailBody) > BODY_TRUNCATE_LENGTH:
return self._clean_body(self._emailBody[:BODY_TRUNCATE_LENGTH])
else:
return self._clean_body(self._emailBody)
def _clean_body(self,dirty):
'''this method simply deletes any occurrence of an '=20' that plagues my output after much testing this is not related to the line return issue, even if i comment it out I still have the problem.'''
dirty=str(dirty)
dirty=dirty.replace(r"=20","")
return r"%s"%dirty
I suggest to add a debug output to your program, dumping character codes before insertion in DB. There are chances that Jython replace CrLf pair with single character and doesn't restore it when written to DB.
You should look at the quopri module (and others regarding email) so you don't have to use dirty tricks as _clean_body

Categories