Summary of Oracle Database LOB fields in the J2EE program

xiaoxiao2021-03-06  42

Recently, in J2EE projects, you need to save text information and pictures and files in J2EE. You have searched it online, there are still a lot, look at it carefully, but you are not very full, there are mistakes, after a few days of practice, Solve the problem, and conclude it, I hope to be aware of the needs of the friends.

There are two main CLOBs and BLOBs we use in LOB, we discuss two types

1.Clob is a characteristic LOB, mainly stores text information, the longest

4G

In the J2EE program, the character information in the textarea in the web page is relatively long. When the VARCHAR2 field type cannot be satisfied, we have to use the Clob data type, and our project will encounter this situation. Now let's talk How to access a Clob field

Now I want to save the information of the textarea element in the web page into the clob field of the database, we all know that the information in the textarea can certainly not be directly saved into clob, we get the String type in the background, not to say, we still Take an example!

Built first in the Test table, the table has 2 fields: ID, Contents, where Contents saves the text data for the Clob type.

Create Table Test (ID Varchar2 (18) Not Null, Contents Clob,)

Then we write a Test JSP file clobtest.jsp, code as follows

<% @ page language = "java" contenttype = "text / html; charSet = GB2312"%>

Clob object Access test </ Title></p> <p></ hEAD></p> <p><body></p> <p><form name = "test" method = "post" Action = "clobtest.action"></p> <p><table width = "80%" Height = "88" border = "0" align = "center" cellpadding = "0" cellspacing = "0"></p> <p><tr></p> <p><td height = "30" align = "center"> Enter ID number <input type = "text" Name = "ID"></p> <p></ TR></p> <p><tr></p> <p><TD align = "center"></p> <p><textarea rows = "28" cols = "68" name = "contents"></p> <p>Registered users must follow:</p> <p>Respect the personal privacy of members, protecting the privacy of membership is a basic policy of 9CBS, 9CBS will not open, edit, or disclose the registration information of the member, unless the following: (1) According to the national security agency of the People's Republic, the requirements of the public security department And according to the corresponding legal proceedings. (2) Maintain 9CBS trademark ownership and other rights. (3) Trend the safety of members, other societies and social public in emergencies. (4) Serious violation of 9CBS-related regulations. 9CBS reserves the right to end members using network service qualifications, and ensure that the members are still secure all personal privacy.</p> <p></ textarea></p> <p></ td></p> <p></ TR></p> <p><tr> <TD align = "center"></p> <p><Input Type = "Submit" name = "submit" value = "Submit"></p> <p></ td></p> <p></ TR></p> <p></ TABLE></p> <p></ form></p> <p></ body></p> <p></ html></p> <p>Click the "Submit" button, we arrive in the background is the object of 2 string types.</p> <p>String strid = Request.getParameter ("ID");</p> <p>String strcontents = request.getParameter ("Contents");</p> <p>Then we have to do this is how to save String type contents into the CLOB type field in the database!</p> <p>Note: LOB data cannot be directly inserted as other types of data. An empty LOB object must be inserted before insertion, and the CLOB type empty object is EMPTY_CLOB (), the blob type empty object is EMPTY_BLOB (). Then the select command query gets the previously inserted record and locks, followed by modifying the empty object to the LOB object to be inserted.</p> <p>// Let's insert an empty CLOB object first</p> <p>Public int insertemptyclob () throws exception {</p> <p>Statement Statement = NULL;</p> <p>INTINTRESULT = -1;</p> <p>Try {</p> <p>// Create a database operation statement</p> <p>Statement = connection.createstatement ();</p> <p>/ / Define SQL statements</p> <p>String strsql = "INSET INTO TEST (ID, Contents) VALUES (Strid, EMPTY_CLOB ()";</p> <p>/ / Execute SQL statement</p> <p>IntResult = statement.executeUpdate (strsql);</p> <p>System.out.println ("intResult valus is" intResult);</p> <p>Return intResult;</p> <p>} catch (exception e) {</p> <p>E.PrintStackTrace ();</p> <p>Return -1;</p> <p>} finally {</p> <p>IF (statement! = null) {</p> <p>STATEMENT.CLOSE ();</p> <p>}</p> <p>}</p> <p>}</p> <p>// Insert StrContent into the Clob field</p> <p>Public void insertclob () throws exception {</p> <p>Statement Statement = NULL;</p> <p>ResultSet ResultSet = NULL;</p> <p>Try {</p> <p>// Settings not submit</p> <p>Connection.SetAutocommit (False);</p> <p>// Create a database operation statement</p> <p>Statement = connection.createstatement ();</p> <p>/ / Define SQL statements</p> <p>String strsql = "SELECT Contents from test where id = strid" "</p> <p>ResultSet = Statement.executeQuery (strsql);</p> <p>Oracle.sql.clob contents = null;</p> <p>While (resultSet.next ()) {</p> <p>/ / Remove the Clob object</p> <p>Contents = (Oracle.Sql.Clob) ResultSet.GetClob ("Contents");</p> <p>}</p> <p>Writer out = contents.getcharacteroutputstream ();</p> <p>Out.write (strcontents); out.flush ();</p> <p>Out.close ();</p> <p>// Database Submit</p> <p>CONNECTION.COMMIT ();</p> <p>} catch (exception e) {</p> <p>E.PrintStackTrace ();</p> <p>} finally {</p> <p>IF (ResultSet! = null) {</p> <p>ResultSet.Close ();</p> <p>}</p> <p>IF (statement! = null) {</p> <p>STATEMENT.CLOSE ();</p> <p>}</p> <p>}</p> <p>}</p> <p>OK, we have saved this text in the form of a Clob field. In practical applications, if you want to save or modify a record, we have to do 2 steps, save or modify the field of non-Lob field type, Save or modify the LOB field! Next we come to read the Clob field you just saved to the database to the JSP page.</p> <p>When we are saved, the Clob field will save the text in TEXTAREA in the original format (including space) to the Clob field, when you read it, we will follow it in the original format (I here I have Use a small treatment method, but if you have a better way, please tell me). Here we read Clob to StringBuffer, in order to save different lines, I add a "&" character between the lines to distinguish. Finally transform into string</p> <p>Put it in VO to ensure the consistency of data transfer from the background to the front desk from the front desk to the background! code show as below:</p> <p>/ **</p> <p>* Get the CLOB text object</p> <p>* @Param SBSQL</p> <p>* @Return</p> <p>* @Throws java.lang.exception</p> <p>* /</p> <p>Public string selectincludeclob (stringbuffer sbsql) throws exception {</p> <p>Statement Stmt = NULL;</p> <p>ResultSet RS = NULL;</p> <p>StringBuffer sbresult = new stringbuffer ();</p> <p>Try {</p> <p>// Setting the database does not submit</p> <p>//Connection.SetAutocommit (False);</p> <p>// Create a database operation statement</p> <p>STMT = connection.createstatement ();</p> <p>// Get the result set</p> <p>RS = stmt.executequery (sbsql.tostring ());</p> <p>While (rs.next ()) {</p> <p>Clob Clob = (Clob) Rs.getClob ("Contents");</p> <p>Reader isclob = Clob.getCharacterstream ();</p> <p>BufferedReader Bfclob = New BufferedReader (isclob);</p> <p>String strclob = bfclob.readline ();</p> <p>While (STRCLOB! = null) {</p> <p>SBRESULT.APPEND (STRCLOB);</p> <p>SBRESULT.APPEND ("&");</p> <p>STRCLOB = bfclob.readline ();</p> <p>}</p> <p>}</p> <p>// Submit a transaction</p> <p>// Connection.commit ();</p> <p>} catch (exception e) {</p> <p>E.PrintStackTrace ();</p> <p>Throw e;</p> <p>} finally {</p> <p>IF (rs! = null) {</p> <p>Rs.close ();</p> <p>}</p> <p>IF (stmt! = null) {</p> <p>Stmt.close ();</p> <p>}</p> <p>}</p> <p>Return sbresult.tostring ();</p> <p>}</p> <p>In the JSP page, we get the text information from VO.</p> <p><textarea rows = "42" cols = "68" name = "contents" style = "border-style: solId; border-color: #ffffff; font-family: imitation Song _GB2312; font-size:</p> <p>14pt</p> <p>Line-Height: 200%; Margin-Top: 8; Margin-Bottom: 6 "></p> <p><%</p> <p>String content = vol. GetContent ();</p> <p>String [] ContentArray = Content.Split ("&");</p> <p>For (int i = 0; i <contentARRAY.LENGTH; i ) {</p> <p>String s = contentArray [i];</p> <p>Out.println (s);</p> <p>}</p> <p>%></p> <p></ textarea></p> <p>This way we guarantee what format is displayed in what format.</p> <p>2. BLOB field, binary LOB, main storage binary data, the longest</p> <p>4G</p> <p>In the J2EE program, it is generally similar to the preservation of pictures and files. Of course, there is another way to save pictures and files on the hard disk, and only the link address of the image and the path on the server in the database. If you encounter files and pictures, it is important to save to the database (for example, when we do the land resources project, there are many pictures, files are important, you need to save to the database), below I write a saved file to the database The blob field and the method of getting a file from the BLOB field of the database (of course, you have to do other jobs, you don't have much to say, if you don't know, you can ask me):</p> <p>/ **</p> <p>* Save the uploaded file to the database of the database.</p> <p>* @Param stratablename Corresponding table name</p> <p>* @Param strcolumnname Saves Saves BLOB field name</p> <p>* @Param INPUTSTREAM Enter the file stream</p> <p>* @Param Sbsqlwhere Where Conditions</p> <p>* @Throws java.lang.exception</p> <p>* /</p> <p>Public Static Void FileUpload (String Strtablename,</p> <p>String strcolumnname,</p> <p>InputStream InputStream,</p> <p>StringBuffer Sbsqlwhere)</p> <p>Throws exception {</p> <p>Connection con = NULL;</p> <p>ResultSet ResultSet = NULL;</p> <p>Statement Stmt = NULL;</p> <p>Try {</p> <p>/ / Get database connections</p> <p>Con = dbconnector.getConnection ();</p> <p>/ / Build a query statement</p> <p>StringBuffer SBSQL = New StringBuffer ();</p> <p>SBSQL.Append ("Update");</p> <p>SBSQL.Append (StrtAblename);</p> <p>SBSQL.Append ("set");</p> <p>SBSQL.Append (strcolumnname);</p> <p>SBSQL.Append ("= EMPTY_BLOB ()");</p> <p>SBSQL.Append (Sbsqlwhere);</p> <p>System.out.println ("Update SQL Value Is *******" SBSQL.TOString ());</p> <p>// Get database operation statement stmt = con.createstatement ();</p> <p>// Insert an empty blob object</p> <p>Stmt.executeUpdate (sbsql.tostring ());</p> <p>Con.SetAutocommit (False);</p> <p>Stringbuffer sbsqlblob = new stringbuffer ();</p> <p>SBSQLBLOB.APpend ("SELECT");</p> <p>SBSQLBLOB.APpend (strcolumnname);</p> <p>SBSQLBLOB.APpend ("from");</p> <p>SBSQLBLOB.APpend (Strtables);</p> <p>Sbsqlblob.Append (sbsqlwhere);</p> <p>SBSQLBLOB.APpend ("for update");</p> <p>System.out.println ("SELECT SQL VALUE IS *********" SBSQL.TOString ());</p> <p>ResultSet = Stmt.executeQuery (sbsqlblob.tostring ());</p> <p>While (resultSet.next ()) {</p> <p>/ * Remove this BLOB object * /</p> <p>Oracle.Sql.blob Blob = (Oracle.Sql.blob) ResultSet.Getblob ("Body");</p> <p>/ * Write data to the BLOB object * /</p> <p>BufferedoutputStream out = new bufferedoutputstream (blob.getbinaryoutputstream ());</p> <p>BufferedInputStream in = New BufferedInputStream (InputStream);</p> <p>INT C;</p> <p>While ((c = in.read ())! = - 1) {</p> <p>Out.write (c);</p> <p>}</p> <p>In.Close ();</p> <p>Out.close ();</p> <p>}</p> <p>Con.SetAutocommit (False);</p> <p>C.Commit ();</p> <p>} catch (exception ex) {</p> <p>EX.PrintStackTrace ();</p> <p>Throw EX;</p> <p>} finally {</p> <p>IF (stmt! = null) {</p> <p>Stmt.close ();</p> <p>}</p> <p>IF (ResultSet! = null) {</p> <p>ResultSet.Close ();</p> <p>}</p> <p>IF (con! = null) {</p> <p>C. close ();</p> <p>}</p> <p>}</p> <p>}</p> <p>The following method is to get the input stream of uploaded files from the database, write the input stream into the servlet stream, and then get it from the page, servlet is not written.</p> <p>/ **</p> <p>* Method Description: Get the file data uploaded by the database</p> <p>*</p> <p>* Enter parameters: 1: Table name (String)</p> <p>* 2: Field name (String)</p> <p>* 3: WHERE condition (StringBuffer)</p> <p>* 5: ServletOutputStream)</p> <p>*</p> <p>* Output parameters: void</p> <p>* editor: */</p> <p>Public static void getDownfile (String Strtables,</p> <p>String strcolumnname,</p> <p>StringBuffer sbsqlwhere,</p> <p>ServletOutputStream Sos) throws exception {</p> <p>Connection con = NULL;</p> <p>PreparedStatement PS = NULL;</p> <p>ResultSet ResultSet = NULL;</p> <p>Try {</p> <p>/ / Get database connections</p> <p>Con = dbconnector.getConnection ();</p> <p>StringBuffer SBSQL = New StringBuffer ();</p> <p>/ / Build a query statement</p> <p>SBSQL.Append ("SELECT" STRCOLUMNAME "from" startAblename);</p> <p>SBSQL.Append (Sbsqlwhere);</p> <p>System.out.println ("SQL Value IS:" SBSQLwhere.toString ());</p> <p>PS = con.preparestatement (sbsql.tostring ());</p> <p>// Execute Query</p> <p>ResultSet = ps.executeQuery ();</p> <p>While (resultSet.next ()) {</p> <p>// Read the data stream</p> <p>InputStream IS = ResultSet.GetBinaryStream (strcolumnname);</p> <p>BYTE [] BUF = New byte [2048];</p> <p>While (is.read (buf)! = - 1) {</p> <p>// Write the data stream to the block of servlet in the output stream of the servlet.</p> <p>SOS.WRITE (BUF);</p> <p>}</p> <p>}</p> <p>} catch (exception ex) {</p> <p>EX.PrintStackTrace ();</p> <p>Throw EX;</p> <p>} finally {</p> <p>IF (ps! = null) {</p> <p>ps.close ();</p> <p>}</p> <p>IF (ResultSet! = null) {</p> <p>ResultSet.Close ();</p> <p>}</p> <p>IF (con! = null) {</p> <p>C. close ();</p> <p>}</p> <p>}</p> <p>}</p> <p>The picture is saved, the file is saved, if you don't know, you can contact me.</p> <p>postscript:</p> <p>Usually, I am busy doing projects. When I am idle, I always want to sum up some of my problems and solutions, but I have never finished, this is the first time I wrote, write bad or unclear places Please bear with the next improvement, I also hope that everyone will make more opinions, everyone will make progress! ! ! ! ! ! ! ! ! ! !</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-72014.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="72014" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.047</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'ljfeyXpxHu2lke_2BVKAKuh4CWf_2BJ4I4UKfghRxFR2WA7moIYGthv8m6KYlnAWurZLDkEUt3Z_2B_2BzW5tatpoRDGyQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>