Execute/ Call Oracle Procedure In C# [duplicate] - c#

How does one call a stored procedure in oracle from C#?

Please visit this ODP site set up by oracle for Microsoft OracleClient Developers:
http://www.oracle.com/technetwork/topics/dotnet/index-085703.html
Also below is a sample code that can get you started to call a stored procedure from C# to Oracle. PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT is the stored procedure built on Oracle accepting parameters PUNIT, POFFICE, PRECEIPT_NBR and returning the result in T_CURSOR.
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
public DataTable GetHeader_BySproc(string unit, string office, string receiptno)
{
using (OracleConnection cn = new OracleConnection(DatabaseHelper.GetConnectionString()))
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.InitialLONGFetchSize = 1000;
cmd.CommandText = DatabaseHelper.GetDBOwner() + "PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("PUNIT", OracleDbType.Char).Value = unit;
cmd.Parameters.Add("POFFICE", OracleDbType.Char).Value = office;
cmd.Parameters.Add("PRECEIPT_NBR", OracleDbType.Int32).Value = receiptno;
cmd.Parameters.Add("T_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}

I have now got the steps needed to call procedure from C#
//GIVE PROCEDURE NAME
cmd = new OracleCommand("PROCEDURE_NAME", con);
cmd.CommandType = CommandType.StoredProcedure;
//ASSIGN PARAMETERS TO BE PASSED
cmd.Parameters.Add("PARAM1",OracleDbType.Varchar2).Value = VAL1;
cmd.Parameters.Add("PARAM2",OracleDbType.Varchar2).Value = VAL2;
//THIS PARAMETER MAY BE USED TO RETURN RESULT OF PROCEDURE CALL
cmd.Parameters.Add("vSUCCESS", OracleDbType.Varchar2, 1);
cmd.Parameters["vSUCCESS"].Direction = ParameterDirection.Output;
//USE THIS PARAMETER CASE CURSOR IS RETURNED FROM PROCEDURE
cmd.Parameters.Add("vCHASSIS_RESULT",OracleDbType.RefCursor,ParameterDirection.InputOutput);
//CALL PROCEDURE
con.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
cmd.ExecuteNonQuery();
//RETURN VALUE
if (cmd.Parameters["vSUCCESS"].Value.ToString().Equals("T"))
{
//YOUR CODE
}
//OR
//IN CASE CURSOR IS TO BE USED, STORE IT IN DATATABLE
con.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
Hope this helps

It's basically the same mechanism as for a non query command with:
command.CommandText = the name of the
stored procedure
command.CommandType
= CommandType.StoredProcedure
As many calls to command.Parameters.Add as the number of parameters the sp requires
command.ExecuteNonQuery
There are plenty of examples out there, the first one returned by Google is this one
There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection

Connecting to Oracle is ugly. Here is some cleaner code with a using statement. A lot of the other samples don't call the IDisposable Methods on the objects they create.
using (OracleConnection connection = new OracleConnection("ConnectionString"))
using (OracleCommand command = new OracleCommand("ProcName", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("ParameterName", OracleDbType.Varchar2).Value = "Your Data Here";
command.Parameters.Add("SomeOutVar", OracleDbType.Varchar2, 120);
command.Parameters["return_out"].Direction = ParameterDirection.Output;
command.Parameters.Add("SomeOutVar1", OracleDbType.Varchar2, 120);
command.Parameters["return_out2"].Direction = ParameterDirection.Output;
connection.Open();
command.ExecuteNonQuery();
string SomeOutVar = command.Parameters["SomeOutVar"].Value.ToString();
string SomeOutVar1 = command.Parameters["SomeOutVar1"].Value.ToString();
}

This Code works well for me calling oracle stored procedure
Add references by right clicking on your project name in solution explorer >Add Reference >.Net then Add namespaces.
using System.Data.OracleClient;
using System.Data;
then paste this code in event Handler
string str = "User ID=username;Password=password;Data Source=Test";
OracleConnection conn = new OracleConnection(str);
OracleCommand cmd = new OracleCommand("stored_procedure_name", conn);
cmd.CommandType = CommandType.StoredProcedure;
--Ad parameter list--
cmd.Parameters.Add("parameter_name", "varchar2").Value = value;
....
conn.Open();
cmd.ExecuteNonQuery();
And its Done...Happy Coding with C#

In .Net through version 4 this can be done the same way as for SQL Server Stored Procs but note that you need:
using System.Data.OracleClient;
There are some system requirements here that you should verify are OK in your scenario.
Microsoft is deprecating this namespace as of .Net 4 so third-party providers will be needed in the future. With this in mind, you may be better off using Oracle Data Provider for .Net (ODP.NET) from the word go - this has optimizations that are not in the Microsoft classes. There are other third-party options, but Oracle has a strong vested interest in keeping .Net developers on board so theirs should be good.

Instead of
cmd = new OracleCommand("ProcName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
You can also use this syntax:
cmd = new OracleCommand("BEGIN ProcName(:p0); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
Note, if you set cmd.BindByName = False (which is the default) then you have to add the parameters in the same order as they are written in your command string, the actual names are not relevant. For cmd.BindByName = True the parameter names have to match, the order does not matter.
In case of a function call the command string would be like this:
cmd = new OracleCommand("BEGIN :ret := ProcName(:ParName); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ret", OracleDbType.RefCursor, ParameterDirection.ReturnValue);
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
// cmd.ExecuteNonQuery(); is not needed, otherwise the function is executed twice!
var da = new OracleDataAdapter(cmd);
da.Fill(dt);

Below worked for me in .NET Core solution. Note that it uses OracleDataReader and Oracle CommandType is CommandType.Text
using Oracle.ManagedDataAccess.Client;
.......
string spSql = "BEGIN STORED_PROC_NAME(:IN_PARAM, :OUT_PARAM1, :OUT_PARAM2); END; ";
using (OracleConnection oraCnn = new OracleConnection(cnnString))
using (OracleCommand oraCommand = new OracleCommand(spSql, oraCnn))
{
await oraCnn.OpenAsync(cancellationToken);
oraCommand.CommandType = CommandType.Text;
oraCommand.BindByName = true;
oraCommand.Parameters.Add("IN_PARAM", OracleDbType.Long, ParameterDirection.Input).Value = 123;
oraCommand.Parameters.Add("OUT_PARAM1", OracleDbType.Int32, null, ParameterDirection.Output);
oraCommand.Parameters.Add("OUT_PARAM2", OracleDbType.Varchar2, 4000, null, ParameterDirection.Output);
OracleDataReader objReader = oraCommand.ExecuteReader();
string outParamValue= oraCommand.Parameters["OUT_PARAM2"].Value.ToString();
}

Related

C# Npgsql read cursor from procedure output parameter

I'm migration an application from a Oracle DB to a Postgres DB.
There are many procedures implemented that returns via output parameter a RefCursor. Just like this:
string schema = server.SERVER_SCHEMA;
string connStr = modelUtils.GetRemoteConn(server, false);
OracleConnection conn = GetConnection(connStr);
OracleCommand cmd = GetCommand(conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = schema + ".ProcedureName";
cmd.Parameters.Add("p_flow", OracleDbType.Varchar2, ParameterDirection.Input).Value = flowKey;
OracleParameter outCursor = cmd.Parameters.Add("p_cursor", OracleDbType.RefCursor, ParameterDirection.Output);
cmd.ExecuteNonQuery();
OracleRefCursor dataCursor = (OracleRefCursor)outCursor.Value;
OracleDataAdapter myAdapter = new OracleDataAdapter("", conn);
myAdapter.Fill(tableData, dataCursor);
Please notice thant I've to grab the parameter outCursor, cast as OracleRefCursor and set it to DataTable named "tableData" via DataAdapter.
To do the same but using Npgsql this is my approach:
string schema = server.SERVER_SCHEMA;
string connStr = modelUtils.GetRemoteConn(server, false);
NpgsqlConnection conn = GetConnection(connStr);
NpgsqlCommand cmd = GetCommand(conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = schema + ".ProcedureName";
cmd.Parameters.Add("p_flow", NpgsqlDbType.Varchar).Value = flowKey;
NpgsqlParameter outCursor = cmd.Parameters.Add(new NpgsqlParameter("p_cursor", NpgsqlDbType.Refcursor) { Direction = ParameterDirection.Output });
cmd.ExecuteNonQuery();
var dataCursor = (Refcursor)outCursor.Value;
NpgsqlDataAdapter myAdapter = new NpgsqlDataAdapter("", conn);
myAdapter.Fill(tableData, dataCursor);
But unfortunately seems that there is no equivalent in Npgsql for Refcursor
Any ideias how can I get arround this?
Thank you.
To everyone who needs to do the same, I recommend reading this: https://stackoverflow.com/a/47970680/2229993
Nonetheless this is how I solved this issue:
NpgsqlConnection conn = GetConnection(connStr);
NpgsqlCommand cmd = new NpgsqlCommand("CALL show_citiesProc('op');FETCH ALL IN \"op\";", conn);
NpgsqlDataAdapter myAdapter = new NpgsqlDataAdapter(cmd);
myAdapter.Fill(tableData);
myAdapter.Dispose();

How to use DataAdapter to call a stored procedure in C# with variable parameters

I am calling the following code in C# to fill a dataAdapter with a given stored procedure "sp1_name". The problem is that I want to call different stored procedures with different parameters. (All SP's do a SELECT)
Let's suppose that my stored procedure name is "SP_SOMESP", then everything works fine.
Let's suppose that my stored procedure name is "SP_SOMESP #Month= 10, #Year = 2010", then it doesn't work. It throws an exception that cannot find this stored procedure.
Any solutions?
Thanks!
//First Connection - SP1
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sp1_name, con)) //sp1_name = NAME + PARAMETERS
{
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.Fill(results2);
}
}
}
First Issue:
Parameters in a stored procedure shouldn't be included along with its name
Second Issue:
Having a space in names of stored procedure isn't a good practice.
And for code behind
using(SqlConnection con = new SqlConnection("Your Connection String Here"))
{
SqlCommand cmd = new SqlCommand("sp_SomeName", con);
cmd.CommandType = CommandType.StoredProcedure;
//the 2 codes after this comment is where you assign value to the parameters you
//have on your stored procedure from SQL
cmd.Parameters.Add("#MONTH", SqlDbType.VarChar).Value = "someValue";
cmd.Parameters.Add("#YEAR", SqlDbType.VarChar).Value = "SomeYear";
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataSet ds = new SqlDataSet();
da.Fill(ds); //this is where you put values you get from the Select command to a
//dataset named ds, reason for this is for you to fetch the value from DB to code behind
foreach(DataRow dr in ds.Tables[0].Rows) // this is where you run through the dataset and get values you want from it.
{
someTextBox.Text = dr["Month"].ToString(); //you should probably know this code
}
}
You have to add in the parameters programmatically, see SqlCommand.Parameters.
It would be something like
cmd.Parameters.AddWithValue("#Month", 10);
cmd.Parameters.AddWithValue("#Year", 2010);
This would be after the command is declared and before it is executed.
If you find that you need to delcare the data type, then try it this way
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = 10;
Check this,
using (SQLCommand cmd = new SQLCommand())
{
cmd.CommandText = "SP_SOMESP";
cmd.Parameters.Add("#Month", 10);
cmd.Parameters.Add("#Year", 2010);
cmd.CommandTimeout = 3600;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
}
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(results2);
}

how to get oracle stored procedure standard output in c#

I am trying to get the stand output in c# returned from oracle stored procedure. dbms_output.put_line('Hello Word')
The c# code i am using is
using (OracleConnection con = new OracleConnection())
{
con.ConnectionString = My_connection_string;
con.Open();
OracleCommand cmd = new OracleCommand("tmp_test", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
var result = cmd.ExecuteScalar();
}
The oracle stored procedure code is
create or replace procedure tmp_test as
v_count integer;
begin
dbms_output.put_line('Hello Word');
end;
The stored procedure execute successfully but I can't get the Hello Word back.
After some struggle i have managed to find the answer and decided to post that might help other.
using (OracleConnection con = new OracleConnection())
{
con.ConnectionString = My_connection_string;
con.Open();
OracleCommand cmd = new OracleCommand("tmp_test", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
var result = cmd.ExecuteScalar();
//it is included dbms_output
cmd.CommandText = "begin dbms_output.enable (1000); end;";
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
string out_string;
int status = 0;
cmd.CommandText = "BEGIN DBMS_OUTPUT.GET_LINE (:out_string, :status); END;";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Clear();
cmd.Parameters.Add("out_string", OracleType.VarChar, 32000);
cmd.Parameters.Add("status", OracleType.Double);
cmd.Parameters[0].Direction = System.Data.ParameterDirection.Output;
cmd.Parameters[1].Direction = System.Data.ParameterDirection.Output;
cmd.ExecuteNonQuery();
out_string = cmd.Parameters[0].Value.ToString();
status = int.Parse(cmd.Parameters[1].Value.ToString());
}
Here's a link to a the documentation for DBMS_OUTPUT package in Oracle - DBMS_OUTPUT
It specifically states that it's used for debugging Oracle Stored Procedures and that this is in essence a debug buffer that you need to actively poll use GET_LINES in order to see the output.
Function in PL/SQL should be something like this:
create or replace function tmp_test as
begin
RETURN 'Hello World';
end;

Calling Oracle stored procedure from C#?

How does one call a stored procedure in oracle from C#?
Please visit this ODP site set up by oracle for Microsoft OracleClient Developers:
http://www.oracle.com/technetwork/topics/dotnet/index-085703.html
Also below is a sample code that can get you started to call a stored procedure from C# to Oracle. PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT is the stored procedure built on Oracle accepting parameters PUNIT, POFFICE, PRECEIPT_NBR and returning the result in T_CURSOR.
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
public DataTable GetHeader_BySproc(string unit, string office, string receiptno)
{
using (OracleConnection cn = new OracleConnection(DatabaseHelper.GetConnectionString()))
{
OracleDataAdapter da = new OracleDataAdapter();
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.InitialLONGFetchSize = 1000;
cmd.CommandText = DatabaseHelper.GetDBOwner() + "PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("PUNIT", OracleDbType.Char).Value = unit;
cmd.Parameters.Add("POFFICE", OracleDbType.Char).Value = office;
cmd.Parameters.Add("PRECEIPT_NBR", OracleDbType.Int32).Value = receiptno;
cmd.Parameters.Add("T_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
}
I have now got the steps needed to call procedure from C#
//GIVE PROCEDURE NAME
cmd = new OracleCommand("PROCEDURE_NAME", con);
cmd.CommandType = CommandType.StoredProcedure;
//ASSIGN PARAMETERS TO BE PASSED
cmd.Parameters.Add("PARAM1",OracleDbType.Varchar2).Value = VAL1;
cmd.Parameters.Add("PARAM2",OracleDbType.Varchar2).Value = VAL2;
//THIS PARAMETER MAY BE USED TO RETURN RESULT OF PROCEDURE CALL
cmd.Parameters.Add("vSUCCESS", OracleDbType.Varchar2, 1);
cmd.Parameters["vSUCCESS"].Direction = ParameterDirection.Output;
//USE THIS PARAMETER CASE CURSOR IS RETURNED FROM PROCEDURE
cmd.Parameters.Add("vCHASSIS_RESULT",OracleDbType.RefCursor,ParameterDirection.InputOutput);
//CALL PROCEDURE
con.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
cmd.ExecuteNonQuery();
//RETURN VALUE
if (cmd.Parameters["vSUCCESS"].Value.ToString().Equals("T"))
{
//YOUR CODE
}
//OR
//IN CASE CURSOR IS TO BE USED, STORE IT IN DATATABLE
con.Open();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dt);
Hope this helps
It's basically the same mechanism as for a non query command with:
command.CommandText = the name of the
stored procedure
command.CommandType
= CommandType.StoredProcedure
As many calls to command.Parameters.Add as the number of parameters the sp requires
command.ExecuteNonQuery
There are plenty of examples out there, the first one returned by Google is this one
There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection
Connecting to Oracle is ugly. Here is some cleaner code with a using statement. A lot of the other samples don't call the IDisposable Methods on the objects they create.
using (OracleConnection connection = new OracleConnection("ConnectionString"))
using (OracleCommand command = new OracleCommand("ProcName", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("ParameterName", OracleDbType.Varchar2).Value = "Your Data Here";
command.Parameters.Add("SomeOutVar", OracleDbType.Varchar2, 120);
command.Parameters["return_out"].Direction = ParameterDirection.Output;
command.Parameters.Add("SomeOutVar1", OracleDbType.Varchar2, 120);
command.Parameters["return_out2"].Direction = ParameterDirection.Output;
connection.Open();
command.ExecuteNonQuery();
string SomeOutVar = command.Parameters["SomeOutVar"].Value.ToString();
string SomeOutVar1 = command.Parameters["SomeOutVar1"].Value.ToString();
}
This Code works well for me calling oracle stored procedure
Add references by right clicking on your project name in solution explorer >Add Reference >.Net then Add namespaces.
using System.Data.OracleClient;
using System.Data;
then paste this code in event Handler
string str = "User ID=username;Password=password;Data Source=Test";
OracleConnection conn = new OracleConnection(str);
OracleCommand cmd = new OracleCommand("stored_procedure_name", conn);
cmd.CommandType = CommandType.StoredProcedure;
--Ad parameter list--
cmd.Parameters.Add("parameter_name", "varchar2").Value = value;
....
conn.Open();
cmd.ExecuteNonQuery();
And its Done...Happy Coding with C#
In .Net through version 4 this can be done the same way as for SQL Server Stored Procs but note that you need:
using System.Data.OracleClient;
There are some system requirements here that you should verify are OK in your scenario.
Microsoft is deprecating this namespace as of .Net 4 so third-party providers will be needed in the future. With this in mind, you may be better off using Oracle Data Provider for .Net (ODP.NET) from the word go - this has optimizations that are not in the Microsoft classes. There are other third-party options, but Oracle has a strong vested interest in keeping .Net developers on board so theirs should be good.
Instead of
cmd = new OracleCommand("ProcName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
You can also use this syntax:
cmd = new OracleCommand("BEGIN ProcName(:p0); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
Note, if you set cmd.BindByName = False (which is the default) then you have to add the parameters in the same order as they are written in your command string, the actual names are not relevant. For cmd.BindByName = True the parameter names have to match, the order does not matter.
In case of a function call the command string would be like this:
cmd = new OracleCommand("BEGIN :ret := ProcName(:ParName); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ret", OracleDbType.RefCursor, ParameterDirection.ReturnValue);
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
// cmd.ExecuteNonQuery(); is not needed, otherwise the function is executed twice!
var da = new OracleDataAdapter(cmd);
da.Fill(dt);
Below worked for me in .NET Core solution. Note that it uses OracleDataReader and Oracle CommandType is CommandType.Text
using Oracle.ManagedDataAccess.Client;
.......
string spSql = "BEGIN STORED_PROC_NAME(:IN_PARAM, :OUT_PARAM1, :OUT_PARAM2); END; ";
using (OracleConnection oraCnn = new OracleConnection(cnnString))
using (OracleCommand oraCommand = new OracleCommand(spSql, oraCnn))
{
await oraCnn.OpenAsync(cancellationToken);
oraCommand.CommandType = CommandType.Text;
oraCommand.BindByName = true;
oraCommand.Parameters.Add("IN_PARAM", OracleDbType.Long, ParameterDirection.Input).Value = 123;
oraCommand.Parameters.Add("OUT_PARAM1", OracleDbType.Int32, null, ParameterDirection.Output);
oraCommand.Parameters.Add("OUT_PARAM2", OracleDbType.Varchar2, 4000, null, ParameterDirection.Output);
OracleDataReader objReader = oraCommand.ExecuteReader();
string outParamValue= oraCommand.Parameters["OUT_PARAM2"].Value.ToString();
}

Reusing SqlCommand?

I am not really sure if this is possible or not.
I am currently working on a college project and I have a function that uses stored procedures. I would like to know if it is possible to take the same SqlCommand instance and apply updated parameters to call into the stored procedure again within the same function.
Lets say i have something like this in my code:
myConStr = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
myConn = new SqlConnection(myConStr);
myCommand = new System.Data.SqlClient.SqlCommand("team5UserCurrentBooks3", myConn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#book_id", bookID);
myCommand.Parameters.AddWithValue("#user_id", userID);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
Is it possible to update MyCommand's parameters and call the stored procedure again?
Yes. You'll want to make sure that you call myCommand.Parameters.Clear between each call in order to dump the parameters, but there's nothing stopping you from reusing the object. (I don't use C# often, so this may have an error or two in the text)
myConStr = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
myConn = new SqlConnection(myConStr);
myConn.Open();
myCommand = new System.Data.SqlClient.SqlCommand("team5UserCurrentBooks3", myConn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#book_id", bookID);
myCommand.Parameters.AddWithValue("#user_id", userID);
myCommand.ExecuteNonQuery();
myCommand.Parameters.Clear();
myCommand.CommandText= "NewStoredProcedureName";
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#foo_id", fooId);
myCommand.Parameters.AddWithValue("#bar_id", barId);
mycommand.ExecuteNonQuery();
myCommand.Parameters.Clear();
myCommand.CommandText = " SELECT * FROM table1 WHERE ID = #TID;"
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.AddWithValue("#tid", tId);
SqlReader rdr;
rdr = myCommand.ExecuteReader();
Yes! You can definitely do that. Within a function you can re-use the same connection as well (I don't recommend re-using a connection object for larger scopes, but it is possible).
You could also do something like this:
myConStr = ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString;
using (var cn = new SqlConnection(myConStr) )
using (var cmd = new SqlCommand("team5UserCurrentBooks3", cn) )
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#user_id", SqlDbType.Int).Value = userID;
cmd.Parameters.Add("#book_id", SqlDbType.Int);
cn.Open();
for(int i = 0; i<10; i++)
{
cmd.Parameters["#book_id"].Value = i;
cmd.ExecuteNonQuery();
}
}
This will run the query 10 times and use the same user_id each time it executes, but change the book_id. The using block is just like wrapping your connection in a try/catch to make sure it's closed.

Categories