Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » ADO.NET & Database » How to Execute Oracle Stored Procedures Dynamically in C#

How to Execute Oracle Stored Procedures Dynamically in C#

In this article, I wiil show how we can store schema of stored procedures in an XML file and load and run the stored procedure from UI application using C# and Oracle.

Author Rank :
Page Views : 37296
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

The attached source code shows how to execute stored procedures from a UI application using Oracle 10G and C#. 

I have not commented the code. If you find any problems, feel free to post your comments at the end of this article or contact me by clicking on Contact Author link in the author profile.

using System;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
using System.IO;
namespace sp
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.DataGrid dataGrid1;
private System.Windows.Forms.Button button1;
private DataSet ds;
private Hashtable hash;
private string tableName;
private System.Windows.Forms.ComboBox SPcomboBox;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components
.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SPcomboBox = new System.Windows.Forms.ComboBox();
this.dataGrid1 = new System.Windows.Forms.DataGrid();
this.button1 = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
this.SuspendLayout();
//
// SPcomboBox
//
this.SPcomboBox.Location = new System.Drawing.Point(16, 24);
this.SPcomboBox.Name = "SPcomboBox";
this.SPcomboBox.Size = new System.Drawing.Size(121, 21);
this.SPcomboBox.TabIndex = 0;
this.SPcomboBox.Text = "----Select----";
this.SPcomboBox.SelectedIndexChanged += new System.EventHandler(this.SPcomboBox_SelectedIndexChanged);
//
// dataGrid1
//
this.dataGrid1.DataMember = "";
this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGrid1.Location = new System.Drawing.Point(8, 56);
this.dataGrid1.Name = "dataGrid1";
this.dataGrid1.Size = new System.Drawing.Size(688, 88);
this.dataGrid1.TabIndex = 1;
//
// button1
//
this.button1.Location = new System.Drawing.Point(8, 152);
this.button1.Name = "button1";
this.button1.TabIndex = 2;
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button1_Click);
///
/ Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(712, 406);
this.Controls.Add(this.button1);
this.Controls.Add(this.dataGrid1);
this.Controls.Add(this.SPcomboBox);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
((System
.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application
.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
ds
= new DataSet();
if(File.Exists(ConfigurationSettings.AppSettings["XMLPath"]))
{
try
{
ds
.ReadXml(ConfigurationSettings.AppSettings["XMLPath"]);
}
catch(Exception exp)
{
MessageBox
.Show(exp.ToString());
}
if(ds.Tables.Count > 0)
{
foreach(DataTable spTable in ds.Tables)
SPcomboBox
.Items.Add(spTable.TableName);
}
else
{
MessageBox
.Show("No Schema Available in xml file");
}
}
else
{
MessageBox
.Show("Please put Stored procedure schema file in ConfigurationSettings.AppSettings['XMLPath']");
}
}
private OracleType ReturnType(string val)
{
switch(val.ToLower())
{
case "bfile" : return OracleType.BFile;
case "blob" : return OracleType.Blob;
case "byte" : return OracleType.Byte;
case "char" : return OracleType.Char;
case "datetime" : return OracleType.DateTime;
case "clob" : return OracleType.Clob;
case "float" : return OracleType.Float;
case "cursor" : return OracleType.Cursor;
case "int16" : return OracleType.Int16;
case "int32" : return OracleType.Int32;
case "double" : return OracleType.Double;
case "intervaldaytosecond" : return OracleType.IntervalDayToSecond;
case "nchar" : return OracleType.NChar;
case "nclob" : return OracleType.NClob;
case "nvarchar" : return OracleType.NVarChar;
case "Raw" : return OracleType.Raw;
case "intervalyeartomonth" : return OracleType.IntervalYearToMonth;
case "longraw" : return OracleType.LongRaw;
case "longvarchar" : return OracleType.LongVarChar;
case "number" : return OracleType.Number;
case "rowid" : return OracleType.RowId;
case "sbyte" : return OracleType.SByte;
case "timestamp" : return OracleType.Timestamp;
case "timestamplocal" : return OracleType.TimestampLocal;
case "timestampwithtz" : return OracleType.TimestampWithTZ;
case "uint16" : return OracleType.UInt16;
case "uint32" : return OracleType.UInt32;
case "varchar" : return OracleType.VarChar;
}
return OracleType.VarChar;
}
private void button1_Click(object sender, System.EventArgs e)
{
OracleConnection con
= new OracleConnection("Data Source=ORCL;User Id=scott;Password=tiger");
OracleCommand cmd
= new OracleCommand(tableName, con);
cmd
.CommandType = CommandType.StoredProcedure;
if( hash.Count > 0)
{
OracleParameter[] param
= (OracleParameter[])hash[tableName];
for(int index = 0; index < param.Length ; index++)
{
param[index]
.Value = dataGrid1[0, index];
cmd
.Parameters.Add(param[index]);
}
}
try
{
con
.Open();
cmd
.ExecuteNonQuery();
MessageBox
.Show("Successfully Done");
}
catch(Exception exp)
{
MessageBox
.Show(exp.ToString());
}
finally
{
cmd
.Parameters.Clear();
cmd
.Dispose();
con
.Close();
}
}
private void SPcomboBox_SelectedIndexChanged(object sender, System.EventArgs e)
{
tableName
= SPcomboBox.Items[SPcomboBox.SelectedIndex].ToString();
BindParameters();
}
private void BindParameters()
{
hash
= new Hashtable();
dataGrid1
.DataSource = ds.Tables[tableName];
int columnNumber = ds.Tables[tableName].Columns.Count;
if(columnNumber > 0)
{
if(ds.Tables[tableName].Columns[0].ColumnName != "NoParam")
{
OracleParameter[] param
= new OracleParameter[columnNumber];
for(int index = 0; index < columnNumber; index++)
{
param[index]
= new OracleParameter();
param[index]
.OracleType = ReturnType(ds.Tables[tableName].Rows[0][index].ToString());
param[index]
.ParameterName = ds.Tables[tableName].Columns[index].ColumnName;
}
hash
.Add(tableName, param);
}
}
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<StoredProcedure>
<
sp1>
<
EName>varchar</EName>
<
Job>varchar</Job>
<
Sal>numeric</Sal>
<
comm>numeric</comm>
</
sp1>
<
sp2>
<
NoParam></NoParam>
</
sp2>
<
sp3>
<
NoParam></NoParam>
</
sp3>
</
StoredProcedure>

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Ashish Singhal
Ashish has been working as a software engineer since 2002. He has written articles for C# Corner . He specializes in the implementation of client/server, database, graphics and/or Internet-based systems using Visual Studio .NET suite. His area of expertise include: C#, ADO.NET, GDI+, Windows Forms, Web Services, Tablet PC and ASP.NET.Ashish's background includes Master's in Computer Science.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Nice Article by Praveen On December 20, 2005

Very Good Article. Keep it up.

Reply | Email | Modify 
I have a Query by Harsha On October 18, 2007

Hi Prvn,

I am using vb.net(web application) and Oracle as Db.I am calling a stored procedure in a package LDAP_AUTH ,this SP will take 3 input arguments which are varchar2.when I am calling the SP I am getting error.The SP is running fine in SQL * Plus. Pls help me on this.Pls mail me vsrkrishna@ap.savi.com

 

 

procedure login(p_user_id in auth_user.login_id%type, p_password in varchar2, p_client_identifier in Varchar2).

 

 

  I am getting the following error.

 

 ORA-06550: line 1, column 7:

PLS-00201: identifier 'LOGIN' must be declared

ORA-06550: line 1, column 7:

PL/SQL: Statement ignored

 

 

Web.config

 

<appSettings>

            <!--<add key="BaseURLSite" value="http://localhost/SaviReportsWebSite"/>

            <add key="DataSource" value="SRIRAMA-D620"/>

            <add key="UID" value="sa"/>

            <add key="PWD" value="satyam"/>

            <add key="DatabaseName" value="Employee"/>-->

           

            <add key="BaseURLSite" value="http://localhost/SaviReportsWebSite"/>

            <add key="UID" value="rpt$928$syn"/>

            <add key="PWD" value="rpt$928$syn"/>

            <add key="Data Source" value="AURORA"/>

      <add key="ReportService2005WebService.ReportService2005" value="http://localhost/ReportServer/ReportService2005.asmx"/>

      </appSettings>  

 

 

Public Function check_Login(ByVal strLoginIDDesc As String, ByVal strPasswordDesc As String, ByVal strSessionIDDesc As String) As Boolean

                                                  

 

            Dim strSQL As String

            'Dim dsHomePage As DataSet

            Dim OracleParam(2) As OracleParameter

 

 

            Dim blnStatus As Boolean = False

            Dim gStrConnection As String = Nothing

 

            gStrConnection = "Persist Security Info=False;"

            gStrConnection += "Integrated Security=False;"

            gStrConnection += "User ID=" + ConfigurationManager.AppSettings("UID") + ";"

            gStrConnection += "pwd=" + ConfigurationManager.AppSettings("PWD") + ";"

            gStrConnection += "Data Source=" + ConfigurationManager.AppSettings("Data Source")

 

            Dim OracleConnection1 As New OracleConnection(gStrConnection)

            Dim cmd As New OracleCommand

            Dim rowsAffected As Integer

            Dim index As Integer

 

            cmd.CommandText = "ldap_auth.login"

            cmd.CommandType = CommandType.StoredProcedure

            cmd.Connection = OracleConnection1

 

            OracleConnection1.Open()

 

            OracleParam(0) = New OracleParameter("LoginIDDesc", OracleType.LongVarChar)

            OracleParam(0).Direction = ParameterDirection.Input

            OracleParam(0).Value = strLoginIDDesc

 

            OracleParam(1) = New OracleParameter("PasswordDesc", OracleType.LongVarChar)

            OracleParam(1).Direction = ParameterDirection.Input

            OracleParam(1).Value = strPasswordDesc

 

            OracleParam(2) = New OracleParameter("SessionIDDesc", OracleType.LongVarChar)

            OracleParam(2).Direction = ParameterDirection.Input

            OracleParam(2).Value = strSessionIDDesc

 

            Dim UBound As Integer = OracleParam.Length

 

            For index = 0 To UBound - 1

                cmd.Parameters.Add(OracleParam(index))               

            Next

 

            rowsAffected = cmd.ExecuteNonQuery()

 

            OracleConnection1.Close()

 

            If rowsAffected = -1 Then

                blnStatus = True

            End If

 

            Return blnStatus

        End Function 

 

 

Regards,

SriRam.

 

 

Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.