<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/">
    <channel>
        <title>CUBRID Java Stored Procedures</title>
        <link>http://www.cubrid.org/?mid=cubrid_java_stored_procedures</link>
        <description>CUBRID Java Stored Procedures</description>
        <language>en</language>
        <pubDate>Mon, 06 Jun 2011 15:55:41 -0800</pubDate>
        <lastBuildDate>Tue, 14 Jun 2011 11:50:15 -0800</lastBuildDate>
        <generator>XpressEngine 1.4.4.1</generator>
                        										        <item>
            <title>CUBRID Java Stored Procedures</title>
            <dc:creator>admin</dc:creator>
            <link>http://www.cubrid.org/cubrid_java_stored_procedures</link>
            <guid isPermaLink="true">http://www.cubrid.org/cubrid_java_stored_procedures</guid>
                                    <description><![CDATA[<h1>CUBRID Java Stored Procedures</h1> 

<p>The scope of this tutorial is to introduce you some of the CUBRID features regarding database <b>stored procedures</b>.</p> 

<h2>Overview</h2> 

<p>One of the most powerful CUBRID features is the built-in support for <b>stored procedures</b>. If you are not familiar with the concept of “<i>stored procedures</i>”, we recommend that you first read about it, before continuing further with this tutorial; one great place to start is, for example, &nbsp;<a href="http://en.wikipedia.org/wiki/Stored_procedure">http://en.wikipedia.org/wiki/Stored_procedure</a>.</p> 

<table border="1" cellspacing="0" cellpadding="0" style="border-collapse:collapse;border:none" width="100%"> <tbody><tr> <td valign="top" style="border:solid windowtext 1.0pt; background:#F2F2F2; padding:10px;"> <p><b>Note</b>: CUBRID supports only <b>Java</b> stored procedures; it does not support SQL, T-SQL or other programming languages or SQL dialects.</p> </td> </tr> </tbody></table> 

<h2>Why use Stored Procedures?</h2> 

<p>There are many reasons why most of the databases, both commercial and open-source, implement support for stored procedures:</p> 

<p><b>Do things which are not available in “plain” SQL</b>. For example, using Java stored procedures you can:</p> 

<ul>
	<li>Get access to the file system</li>
	<li>Get access to web/web services</li>
	<li>Implement complex business logic</li>
	<li>…and, generally speaking, do whatever things you can do using a powerful development language like Java, for example.</li>
</ul>

<p><b>Share the code/Share the features/Code reuse</b>! While a client-side application is hardly available to another user without some extra-effort, a database stored procedure is a great way to share functionalities. Stored procedures are available on the database server-side, so sharing them is just a matter of providing access to the database.</p> 

<p><b>Enhance CUBRID</b> with new features! Whenever you need a new feature in CUBRID, a great way to start can be through developing a stored procedure. Of course, you could always choose to contribute with your code to the CUBRID engine, but developing a Java stored procedure is much simpler.</p> 

<p>And these are not the only reasons to use stored procedures – think about performance and usability; all these are valid reasons to enhance your CUBRID database with Java stored procedures. </p> 

<h2>“How-To” CUBRID Java Stored Procedures</h2> 

<p>To create a CUBRID stored procedure, the mandatory steps are:</p> 

<ul>
	<li><b><span>Configure the environment</span></b><span> – see </span><a href="/manual/840/en/Environment%20Configuration%20for%20Java%20Stored%20Function|Procedure">http://www.cubrid.org/manual/840/en/Environment%20Configuration%20for%20Java%20Stored%20Function|Procedure</a><span> </span></li> 
	<li><b><span>Enable support for stored procedure</span></b><span> in the database (please note that by default this is “off”); read more at </span><a href="/manual/840/en/How%20to%20Write%20Java%20Stored%20Function|Procedure#conf">http://www.cubrid.org/manual/840/en/How%20to%20Write%20Java%20Stored%20Function|Procedure#conf</a><span> </span></li> 
	<li><b><span>Develop and Compile</span></b><span> the Java stored procedure source code</span></li> 
	<li><b><span>Load</span></b><span> the compiled Java class into the CUBRID database, using the <i>loadjava</i> tool</span></li> 
	<li><span>“<b>Publish</b>” the loaded Java class/Function or Procedure, by defining the SQL interface (the “call specification” – see </span><a href="/manual/840/en/Call%20Specifications">http://www.cubrid.org/manual/840/en/Call%20Specifications</a><span>)</span></li> 
</ul>

<p><span>We will not go here into more details about these steps, because the online/offline documentation already covers this topic in details – see </span><a href="/manual/840/en/How%20to%20Write%20Java%20Stored%20Function|Procedure">http://www.cubrid.org/manual/840/en/How%20to%20Write%20Java%20Stored%20Function|Procedure</a><span>.</span></p> 

<table border="1" cellspacing="0" cellpadding="0" style="border-collapse:collapse;border:none" width="100%"> <tbody><tr> <td valign="top" style="padding: 10px; border:solid windowtext 1.0pt; background:#F2F2F2;"> <p>Some very interesting information about CUBRID Java stored procedures can be found here: <a href="/manual/840/en/Note">http://www.cubrid.org/manual/840/en/Note</a>.&nbsp; </p> </td> </tr> </tbody></table> 

<p>In CUBRID, there are two types of database stored procedures:</p> 

<ul>
	<li><b>Procedures</b>; these are stored procedures which do not return a value</li> 
	<li><b>Functions</b>; these are stored procedures which return a value back to the “caller”</li> 
</ul>

<p align="center" style="text-align:center"><span><img border="0" width="245" height="72" id="Picture 1" src="/files/docs/tutorials/java_stored_procedures/image001.png" editor_component="image_link"/></span></p> 

<p><span>For <b>Functions</b>, the valid data types which can be returned are any of the CUBRID SQL data types (except BLOB/CLOB), or the CURSOR data type (which is used for when the code returns a Java <i>ResultSet</i>):</span></p> 

<p align="center" style="text-align:center"><span><img border="0" width="405" height="177" id="Picture 3" src="/files/docs/tutorials/java_stored_procedures/image002.png" editor_component="image_link"/></span></p> 

<p><span>Beside this difference regarding the return value, there are no other differences that separate <b>procedures</b> and <b>functions</b>. Therefore, unless when explicitly specified, whenever we will refer to “stored procedures” in this document, it means that it applies to both types.</span></p> 

<table border="1" cellspacing="0" cellpadding="0" style="border-collapse:collapse;border:none" width="100%">
	<tbody><tr>
		<td valign="top" style="border:solid windowtext 1.0pt; background:#F2F2F2;padding: 10px;">
			<p><b>Important!</b> There are 2 fundamental types of stored procedures in CUBRID:</p> <p><b>Stored procedures which do not access the CUBRID database</b></p> <p><b>Stored procedures which have access the CUBRID database</b> – so-called “<b>server-side JDBC driver stored procedures</b>”</p>
		</td>
	</tr>
</tbody></table> 

<p>As the scope of developing a stored procedure in a database is generally associated with the need of accessing the data in the database, we will refer in this document only to the second type of stored procedures – which have access to the database.</p> 

<h2>Connecting to the database</h2> 

<p>As a general rule, because a stored procedure is nothing else but Java code, all the rules about connecting and accessing a database via JDBC do apply.</p> 

<p>In particular, because a stored procedure is already “attached” to a database, to connect to the “current” database, all you need to do to get a database connection in code is:</p> 

<div editor_component="code_highlighter" code_type="Java" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false" style="border-width: 1px 1px 1px 5px; border-style: dotted dotted dotted solid; border-color: rgb(102, 102, 102) rgb(102, 102, 102) rgb(102, 102, 102) rgb(34, 170, 238); padding: 5px;">
<p>Connection conn = DriverManager.getConnection("jdbc:default:connection:");</p> 
</div>

<p>Of course, you can connect to any other database as well from the stored procedures code, CUBRID or not, there are no limitations – it is nothing else but standard JDBC programming.</p> 

<p><b>Recommendation</b>: The next thing to do, after successfully connected, is to setup the connection encoding:</p> 

<div editor_component="code_highlighter" code_type="Java" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false" style="border-width: 1px 1px 1px 5px; border-style: dotted dotted dotted solid; border-color: rgb(102, 102, 102) rgb(102, 102, 102) rgb(102, 102, 102) rgb(34, 170, 238); padding: 5px;">
<p>((CUBRIDConnection) conn).setCharset("UTF-8");</p> 
</div>

<p>In the next sections, we will go through some concrete example of developing Java stored procedures.</p> 

<h2>A simple stored procedure example</h2> 

<p>Let’s create a stored procedure, which replicates the COUNT() SQL function; it will get as an input parameter the name of the table and it will return the number of records in that table.</p> 

<p>Here is the (simplified) Java code:</p> 

<div editor_component="code_highlighter" code_type="Java" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false" style="border-width: 1px 1px 1px 5px; border-style: dotted dotted dotted solid; border-color: rgb(102, 102, 102) rgb(102, 102, 102) rgb(102, 102, 102) rgb(34, 170, 238); padding: 5px;">
<p>public static int count(String table_name) throws  Exception {</p> 
<p>String sql = "select count(*) from " + table_name;</p> 
<p>int ret = 0;</p> 
<p></p> 
<p>try {</p> 
<p>Class.forName("cubrid.jdbc.driver.CUBRIDDriver");</p> 
<p>Connection conn = DriverManager.getConnection("jdbc:default:connection:");</p> 
<p>((CUBRIDConnection) conn).setCharset("UTF-8");</p> 
<p>&nbsp;</p> 
<p>PreparedStatement pstmt = conn.prepareStatement(sql);</p> 
<p>ResultSet resultSet = pstmt.executeQuery();</p> 
<p>if (resultSet.next()) {</p> 
<p>ret = resultSet.getInt(1);</p> 
<p>}</p> 
<p>resultSet.close();</p> 
<p>pstmt.close();</p> 
<p>conn.commit();</p> 
<p>conn.close();</p> 
<p>} catch (SQLException e) {</p> 
<p>System.err.println(e.getMessage());</p> 
<p>}</p> 
<p></p>
<p>return ret;</p> 
<p>}</p>
</div>

<p>After compiling the code, we will load the compiled class in the database, using the <i>loadjava</i> utility:</p> 

<p align="center" style="text-align:center"><img border="0" width="559" height="37" id="Picture 6" src="/files/docs/tutorials/java_stored_procedures/image003.png" editor_component="image_link"/></p> 

<p><b>&nbsp;</b></p> 

<p>Then, we need to create the call interface, so we can access the procedure from SQL.</p> 

<p>If you are using CUBRID Manager, you can take advantage of the built-in UI interface:</p> 

<p align="center" style="text-align:center"><img border="0" width="491" height="514" id="Picture 7" src="/files/docs/tutorials/java_stored_procedures/image004.png" editor_component="image_link"/></p> 

<p>Or you can just use plain SQL:</p> 

<div editor_component="code_highlighter" code_type="Sql" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false" style="border-width: 1px 1px 1px 5px; border-style: dotted dotted dotted solid; border-color: rgb(102, 102, 102) rgb(102, 102, 102) rgb(102, 102, 102) rgb(34, 170, 238); padding: 5px;">
<p>CREATE FUNCTION "tcount"("table_name" STRING) RETURN INTEGER</p> 
<p>AS LANGUAGE JAVA</p>
<p>NAME 'information_schema.count(java.lang.String) return java.lang.Int'</p> 
</div>
<p></p>

<table border="1" cellspacing="0" cellpadding="0" style="border-collapse:collapse;border:none" width="100%">
	<tbody><tr>
		<td valign="top" style="border:solid windowtext 1.0pt; background:#EEECE1;padding:10px;">
			<p><b>Note</b>: Because “<b><i>count</i></b>” is a reserved CUBRID keyword, when we declared the access interface, we will named it “<b><i>tcount</i></b>”. However, this restriction applies only to the SQL call interface, in the Java code we can use the “<b><i>count</i></b>” name for the function – there are no restrictions.</p>
		</td>
	</tr>
</tbody></table> 

<p>Once created, you can see the stored procedure in CUBRID Manager:</p> 

<p align="center" style="text-align:center"><img border="0" width="301" height="152" id="Picture 8" src="/files/docs/tutorials/java_stored_procedures/image005.png" editor_component="image_link"/></p> 

<p>…Last step – use it from SQL!</p> 

<p>There are various ways to execute it:</p> 

<div editor_component="code_highlighter" code_type="Sql" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false" style="border-width: 1px 1px 1px 5px; border-style: dotted dotted dotted solid; border-color: rgb(102, 102, 102) rgb(102, 102, 102) rgb(102, 102, 102) rgb(34, 170, 238); padding: 5px;">
<p>select tcount('athlete');</p> 
</div>

<p>or</p> 

<div editor_component="code_highlighter" code_type="Sql" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false" style="border-width: 1px 1px 1px 5px; border-style: dotted dotted dotted solid; border-color: rgb(102, 102, 102) rgb(102, 102, 102) rgb(102, 102, 102) rgb(34, 170, 238); padding: 5px;">
<p>call tcount('athlete');</p> 
</div>

<p>&nbsp;</p> 

<p align="center" style="text-align:center"><img border="0" width="300" height="227" id="Picture 9" src="/files/docs/tutorials/java_stored_procedures/image006.png" editor_component="image_link"/></p> 

<p><b>Note:</b> There are no verifications for the correct data type for the input parameters!</p> 

<p>For example, calling with a numeric argument, will simply output 0, without any error messages:</p> 

<p align="center" style="text-align:center"><img border="0" width="244" height="254" id="Picture 10" src="/files/docs/tutorials/java_stored_procedures/image007.png" editor_component="image_link"/></p> 

<p><b>Remember:</b></p> 

<p>CUBRID stored procedure names are not case sensitive.</p> 

<p>The maximum name length is 256</p> 

<p>The maximum number of parameters a stored procedure can have is 64.</p> 

<h2>Another example: Accessing the file system</h2> 

<p>As we mentioned before, using Java stored procedures gives access to a whole new world of functionalities which are not available from SQL by default - you can use almost all the Java capabilities right from within CUBRID. </p> 

<p>In particular, one important benefit that worth mentioning is getting access from the database to the file system.</p> 

<p>We will illustrate this with an example of a stored procedure which will output data in a file. In particular, because CUBRID is missing an export-to-xml function or a similar built-in tool, let’s create a stored procedure which will take as an input argument a SQL SELECT statement and will output the result set in an XML format.</p> 

<p>We will keep things simple, no XML parsers and a quite simple schema; of course, following this example, you can extend it to create more complex functionality.</p> 

<p>Here is a part of the Java code:</p> 

<div editor_component="code_highlighter" code_type="Java" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false" style="border-width: 1px 1px 1px 5px; border-style: dotted dotted dotted solid; border-color: rgb(102, 102, 102) rgb(102, 102, 102) rgb(102, 102, 102) rgb(34, 170, 238); padding: 5px;">
<p>public static String save_to_xml(String sql, String filename)</p>
<p>throws Exception {</p> 
<p>try {</p> 
<p>Class.forName("cubrid.jdbc.driver.CUBRIDDriver");</p> 
<p>Connection conn = DriverManager.getConnection("jdbc:default:connection:");</p> 
<p>((CUBRIDConnection) conn).setCharset("UTF-8");</p> 
<p>&nbsp;</p> 
<p>File target = new File(filename);</p> 
<p>&nbsp;</p> 
<p>FileWriter fstream = new FileWriter(filename);</p> 
<p>BufferedWriter out = new BufferedWriter(fstream);</p> 
<p>out.write("&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;");</p> 
<p>out.newLine();</p> 
<p>&nbsp;</p> 
<p>…</p> 
<p>PreparedStatement pstmt = conn.prepareStatement(sql);</p> 
<p>ResultSet rs = pstmt.executeQuery();</p> 
<p>&nbsp;</p> 
<p>ResultSetMetaData rsm = rs.getMetaData();</p> 
<p>out.write("&lt;metadata&gt;");</p> 
<p>out.newLine();</p> 
<p>for (int i = 1; i &lt;= rsm.getColumnCount(); i++) {</p> 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.write(" " + "&lt;column&gt;");</p> 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.newLine();</p> 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.write("&nbsp; " + "&lt;name&gt;");</p> 
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.newLine();</p> 
<p>…</p> 
</div>

<p></p>
<table border="1" cellspacing="0" cellpadding="0" style="border-collapse:collapse;border:none" width="100%"> <tbody><tr> <td valign="top" style="border:solid windowtext 1.0pt; background:#EEECE1;padding: 10px;"> <p>The complete code is available for download on this page. You will find not only the examples used in this tutorial, but other stored procedures as well. </p> </td> </tr> </tbody></table> 

<p>After compiling, loading in the database and creating the interface we will be able to use this stored procedure from SQL:</p> 

<p align="center" style="text-align:center"><img border="0" width="602" height="360" id="Picture 11" src="/files/docs/tutorials/java_stored_procedures/image008.jpg" editor_component="image_link"/></p> 

<p>Let’s dump the data from the <b><i>code</i></b> table in the file:</p> 

<div editor_component="code_highlighter" code_type="Java" file_path="" description="" first_line="1" collapse="false" nogutter="false" nocontrols="false" style="border-width: 1px 1px 1px 5px; border-style: dotted dotted dotted solid; border-color: rgb(102, 102, 102) rgb(102, 102, 102) rgb(102, 102, 102) rgb(34, 170, 238); padding: 5px;">
<p>call save_to_xml('select * from code', 'c:\out.xml');</p> 
</div>

<p>And here are the results:</p> 

<p align="center" style="text-align:center"><img border="0" width="601" height="458" id="Picture 13" src="/files/docs/tutorials/java_stored_procedures/image009.png" editor_component="image_link"/></p> 

<table border="1" cellspacing="0" cellpadding="0" style="border-collapse:collapse;border:none" width="100%"> <tbody><tr> <td valign="top" style="border:solid windowtext 1.0pt; background:#EEECE1; padding: 10px;"> <p><b>Tip</b>: &nbsp;If you want to provide some feedback to the user, you can always choose to return a string value (use a function instead of a procedure). For example, you can return a confirmation that the operation has completed ok, or an error message.</p> </td> </tr> </tbody></table> 

<p align="center" style="text-align:center">&nbsp;</p> 

<h2>Summary</h2> 

<p>As you can see, there are so many new things you can accomplish when you combine the power of Java with a CUBRID database! …And there is nothing complicated or hard to do!</p> 

<p>So when you need a new functionality in your application, first consider if a store procedure is a good solution approach.</p> 

<p>Also, you should know that stored procedures are not a universal solution to any problem - they have their own disadvantages:</p> 

<p>Are very hard to debug.</p> 

<p>They can “hide” the business logic, making hard to understand how they work/what do they do exactly.</p> 

<p>There are limitations when combining SQL and Java, especially when you need to deal with result sets.</p> 

<h2>Links &amp; Resources</h2> 

<table border="1" cellspacing="0" cellpadding="0" style="border-collapse:collapse;border:none" width="100%">
	<tbody><tr>
		<td width="200px;" valign="top" style="border:solid windowtext 1.0pt; padding:10px;"> <p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal">CUBRID Online Manual</p> </td>
		<td valign="top" style="border:solid windowtext 1.0pt; border-left:none;padding:10px;"> <p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal"><a href="/webmanual/3.1/">http://www.cubrid.org/webmanual/3.1/</a> </p>
		</td>
	</tr>
	<tr>
		<td valign="top" style="border:solid windowtext 1.0pt; border-top:none;padding:10px;"> <p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal">CUBRID Stored Procedures</p>
		</td>
		<td valign="top" style="border-top:none;border-left: none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt; padding:10px;"> <p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal"><a href="/manual/840/en/How%20to%20Write%20Java%20Stored%20Function|Procedure">http://www.cubrid.org/manual/840/en/How%20to%20Write%20Java%20Stored%20Function|Procedure</a> </p>
		</td>
	</tr>
	<tr>
		<td valign="top" style="border:solid windowtext 1.0pt; border-top:none;padding:10px;"> <p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal">JDBC general information</p>
		</td>
		<td valign="top" style="border-top:none;border-left: none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt; padding:10px;"> <p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal"><a href="http://en.wikipedia.org/wiki/Java_Database_Connectivity">http://en.wikipedia.org/wiki/Java_Database_Connectivity</a> </p>
		</td>
	</tr>
	<tr>
		<td valign="top" style="border:solid windowtext 1.0pt; border-top:none;padding:10px;"> <p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal">CUBRID JDBC &amp; Java Programming with CUBRID</p>
		</td>
		<td valign="top" style="border-top:none;border-left: none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt; padding:10px;"> <p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal"><a href="/cubrid_java_programming">http://www.cubrid.org/cubrid_java_programming</a> </p>
		</td>
	</tr>
	<tr>
		<td valign="top" style="border:solid windowtext 1.0pt; border-top:none;padding:10px;"> <p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal">General information about stored procedures</p>
		</td>
		<td valign="top" style="border-top:none;border-left: none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt; padding:10px;">
			<p style="margin-bottom:0in;margin-bottom:.0001pt;line-height: normal"><a href="http://en.wikipedia.org/wiki/Stored_procedure">http://en.wikipedia.org/wiki/Stored_procedure</a> </p>
		</td>
	</tr>
</tbody></table> 

<p>&nbsp;</p> 

<p>&nbsp;</p> 

<p>This concludes the first <b>CUBRID Java Stored Procedures tutorial</b>. In the next tutorial about CUBRID Stored Procedures, we will see how to use stored procedures which return a result set. Please let us know your feedback and remember to periodically check the CUBRID web site – <a href="/tutorials">www.cubrid.org/tutorials</a> - for more tutorials and resources.</p> 

<p><b>Thank you!</b></p>]]></description>
                        <pubDate>Mon, 06 Jun 2011 14:56:28 -0800</pubDate>
                        <category>java</category>
                        <category>stored procedures</category>
                                </item>
            </channel>
</rss>
