Execute Stored Procedures in JAVA

I really hope this is tutorial is what you really need after google gave many answer. This tutorial was born after helping my friend to do his university task. At first, I really don’t have any idea how to execute stored procedures (I’m using SQL Server 2005) in JAVA application. After searching in internet, I found the easiest tutorial so I can execute SP in my application.

When you read this tutorial, I hope you already understand :

  • Basic JAVA programming
  • Create connection between JAVA and SQL Server

Here my source code :

[code language=”java”]
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Marifnst
*/
public class SampleExecuteSP {
public static void main(String args[]) {
try {
String url = "jdbc:sqlserver://localhost:1433;databaseName=SAMPLE_DATABASE";
String username = "sa";
String password = "";
Connection connection = DriverManager.getConnection(url, username, password);
PreparedStatement ps = connection.prepareStatement("EXEC USP_SAMPLE_STORED_PROCEDURES ?";);
ps.setString(1, "param";);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();

// generate column name
List<String> columns = new ArrayList<>();
for (int i = 1; i <= rsmd.getColumnCount() ; i++) {
columns.add(rsmd.getColumnName(i));
}

while (rs.next()) {
StringBuilder output = new StringBuilder("";);
for (String columnName : columns) {
output.append(rs.getString(columnName)).append(" ";);
}
System.out.println(output);
}
connection.close();
} catch (Exception ex) {
Logger.getLogger(SampleExecuteSP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
[/code]

I hope this tutorial help you.

Marifnst, 2013-05-24

Leave a Reply

Your email address will not be published. Required fields are marked *

Afiseaza emoticoanele Locco.Ro