An array of C#, PHP, and HTML programming articles, tutorials, and resources

Posts Tagged ‘ Java ’

PreparedStatements are used in Java to set up SQL statements. They can be used to insert a set of data to the database or retrieve a set of data from the database.  You can visit the Java API here:  http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html

This is how I’ve used the prepared statement to insert data to the database:

First, import the necessary package:

import java.sql.*;

Create the PreparedStatement object:

PreparedStatement pstmt = null;

Create a  String for your SQL statement. For example:

String insert = "INSERT INTO MYTABLE (COL1, COL2, COL3) VALUES (?, ?, ?)";

The question marks represent values being passed into the statement.

Create a Connection to the database. Usually the URL, username and password are stored in a config file but for simplicity, the following can be done:

Connection con = DriverManager.getConnection("<URL>", "<username>", "<password>");

The URL is something like “jdbc:odbc:<db>”. Username is the schema name, and password is the password.

Then, in a try/catch block,

try (
  pstmt = con.prepareStatement(insert);
  pstmt.setString(1, valCol1);  //valCol1 is the String value being inserted for COL1 in the table MYTABLE
  pstmt.setString(2, valCo2);
  pstmt.setString(3, valCo3);
  pstmt.executeQuery();  //executeQuery() is the method used to run the SQL statement
  con.commit();  //commit() will commit the data into MYTABLE
} catch (SQLException e){
  error("Error inserting into db " + e.getMessage());
}

To retrieve data from the db is similar:

This time, you will need to create a ResultSet object to store the retrieved data:

ResultSet rs = null;

This is an example:

public String[] getData(Connection con, String col3) {
  String select = "SELECT COL1, COL2 FROM MYTABLE WHERE COL3 = ?";
  PreparedStatement ps = null;
  ResultSet rs = null;
  List<String> dataArray = new ArrayList<String>(); //This will contain the data from the db
  try{
    ps = con.prepareStatement(select);
    ps.setString(1,  col3); // col3 is the value being set in the SQL statement
    rs = ps.executeQuery(); //this will execute the query and store the result in rs
    while(rs.next()) {
      dataArray.add(rs.getString(1));
    }
  } catch(SQLException e) {
    error("Unable to get data " , e);
  }
  ps.close()  //close the prepared statement
  con.close()  //close the connection
}

You may have noticed the fancing code snippets that accompany many of the tutorials on this website! I would love to say I developed this myself, but the truth is that this is a free resource free for anybody to download and use. It is called SyntaxHighlighter and can be found at http://code.google.com/p/syntaxhighlighter/.

What is Included?

So what does the Syntax Highlighter come with? Below is a list my favorite features of this software:

  1. It’s completely free!
  2. Associate keywords for supported languages are highlighted.
  3. Each line of code is numbered and colored for easier reading!
  4. Allows one click to code only view.
  5. Allows one click copy to clipboard of code.
  6. Allows one click copy to printer.

What Comes With the Download

The file can be downloaded from their official website at http://code.google.com/p/syntaxhighlighter/ as a rar compressed file. Inside the compressed file, you will find various folders and files. The core files that are required include:

  1. clipboard.swf
  2. shCore.js
  3. SyntaxHighlighter.css

Still, there are many more JavaScript files that have been included in the download. Not all of these files are required. Instead, you choose additional optional JavaScript files for the programming or scripting languages you want the Syntax Highlighter to associate.

Installation After Uploading Files

After you have uploaded the required and accompanying optional files, you will need to include the javascript and css files to the header of the pages with which you plan on using the Syntax Highlighter. See the example below:

<link type="text/css" rel="stylesheet" href="http://www.victorchen.info/wp-includes/js/SyntaxHighlighter/Styles/SyntaxHighlighter.css"></link>
<script language="javascript" src="http://www.victorchen.info/wp-includes/js/SyntaxHighlighter/Scripts/shCore.js"></script>
<script language="javascript" src="http://www.victorchen.info/wp-includes/js/SyntaxHighlighter/Scripts/shBrushCSharp.js"></script>
<script language="javascript" src="http://www.victorchen.info/wp-includes/js/SyntaxHighlighter/Scripts/shBrushJava.js"></script>
<script language="javascript" src="http://www.victorchen.info/wp-includes/js/SyntaxHighlighter/Scripts/shBrushPhp.js"></script>
<script language="javascript" src="http://www.victorchen.info/wp-includes/js/SyntaxHighlighter/Scripts/shBrushXml.js"></script>
<script language="javascript" src="http://www.victorchen.info/wp-includes/js/SyntaxHighlighter/Scripts/shBrushJScript.js"></script>
<script language="javascript">
  window.onload = function () {
    dp.SyntaxHighlighter.ClipboardSwf = 'http://www.victorchen.info/wp-includes/js/SyntaxHighlighter/Scripts/clipboard.swf';
    dp.SyntaxHighlighter.HighlightAll('code');
  }
</script>

In the above, there Line 1 includes the CSS file. Next, Line 2 includes the one core JavaScript file. Lines 4 through 8 include optional JavaScript files. Lines 9 through 14 include setup for using Syntax Highlighter. The portion requires including the clipboard.swf file.

Usage

I assume you already have formatted code contained within the pre tags, as found in a previous tutorial called 3 Steps to Posting Sample Code on your Website. As of now, all you have is a formatted tag, without the fancy upgrades. All you need to add for fancy code formatting is to add name=”code” class=”html”. Exchange html with the type of file you have included. Click to see sample supported files: http://code.google.com/p/syntaxhighlighter/wiki/Languages. An example:

<pre name="code" class="html">&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Victor's Programming Aid&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;p&gt;This is a test&lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;</pre>

Conclusion

With that, you now have fancy code formatting on your website. Comment on some examples of where you have used the Syntax Highlighter in action!

I recently learned how to call a stored procedure using Java.

CallableStatement is used when a Java application needs to call a stored procedure. The stored procedure contains the SQL query to be executed on the database and is stored on the database.

To use CallableStatement, the Java code will need to first import the CallableStatement class.

import java.sql.CallableStatement;

In your method, create a CallableStatement object:

CallableStatement cs = null;

Create a connection with the database:

cs = connection.prepareCall("{ call procedure_name}");

connection is the connection to the database, and prepareCall is the method used to call the stored procedure. The syntax used in the prepareCall parameters is shown above, but replace procedure_name with the actual stored procedure name.

Next, use cs.execute(); to execute. So to put it together, you will need to add it to try/catch block as shown below:

CallableStatement cs = null;
try{
  // The syntax for a stored procedure with no
  // parameters would look like this:
  cs = connection.prepareCall("{ call procedure_name}");
  cs.execute();
} catch (SQLException e) {
}

This is the simplest use of CallableStatement. The stored procedure above does not have any parameters. If the stored procedure has parameters, you will need to modify your code to add the parameters in the Java code. CallableStatements can have IN parameters, OUT parameters, IN/OUT parameters, or no parameters. The Java API for CallableStatement is a good reference as well. Here are some examples I found that are helpful and have the proper syntax:

try {
  // Call a function that takes NO parameters
  cs = connection.prepareCall("{call procedure_name}");
  cs.execute(); //execute the stored procedure

  // Call a function that takes a String IN parameter
  // An IN parameters is when you input a value
  // for the stored procedure

  cs = connection.prepareCall("{call procedure_name_in(?)}");
  cs.setString(1, "ABC"); // Set the value for the IN parameter
  cs.execute();

  // Call a function that returns a String OUT parameter
  // An OUT parameter is when the stored procedure
  // has an output value

  cs = connection.prepareCall("{call procedure_name_out(?)}");
  cs.registerOutParameter(1, Types.VARCHAR);
  // Register the types of the return value and OUT parameter
  cs.execute();
  String outParam = cs.getString(1); // OUT parameter

  // Call a function with one IN/OUT parameter
  // An IN/OUT parameter has been an input and an output

  cs = connection.prepareCall("{call procedure_name_inout(?)}");
  cs.registerOutParameter(1, Types.VARCHAR);
  cs.setString(1, "ABC");
  cs.execute();
  String outParam = cs.getString(1);
} catch (SQLException e) {
}