using this coding,while i give fruitId ,i need to retrieve fruitname,using this it shows some error..any one help...
string constring = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("savefruit11", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#FruitsId", int.Parse(TextBox3.Text.Trim()));
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
}
}
Store procedure for the above code.
use[FruitsDB]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE [dbo].[savefruit11]
#FruitId INT,
#FruitName VARCHAR(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT #FruitName = Fruitsname
FROM Fruits1
WHERE FruitsId = #FruitId
END
cmd.Parameters.Add("#Fruitsname", SqlDbType.VarChar, 50);
cmd.Parameters["#Fruitsname"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
con.Close();
TextBox4.Text = "Fruit Name:"+cmd.Parameters["#FruitName"].Value.ToString();
Your parameter is called #Fruitsname, but you get it back with #FruitName. You have an additional s in the first version. Make them consistent by changing the first #FruitsName to #FruitName which will match what you have in the stored procedure.
Or, as Henk suggested in the comments create a const string to contain your parameter name so that it is consistent across all usages.
Use cmd.ExecuteQuery or cmd.ExecuteScalar
//To Execute SELECT Statement
ExecuteQuery()
//To Execute Other Than Select Statement(means to Execute INSERT/UPDATE/DELETE)
ExecuteNonQuery()
with your udpate
s is missing in parameter name in stored procedure
Use the following example way
using (SqlConnection connection = new SqlConnection())
{
string connectionStringName = this.DataWorkspace.AdventureWorksData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
string procedure = "HumanResources.uspUpdateEmployeePersonalInfo";
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(
new SqlParameter("#EmployeeID", entity.EmployeeID));
command.Parameters.Add(
new SqlParameter("#NationalIDNumber", entity.NationalIDNumber));
command.Parameters.Add(
new SqlParameter("#BirthDate", entity.BirthDate));
command.Parameters.Add(
new SqlParameter("#MaritalStatus", entity.MaritalStatus));
command.Parameters.Add(
new SqlParameter("#Gender", entity.Gender));
connection.Open();
command.ExecuteNonQuery();
}
}
reference from MSDN
http://msdn.microsoft.com/en-us/library/jj635144.aspx
Related
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;
I have this table Profile which has fields with user_Id and regNo and I want to check first if id and email are already exists before proceed to inserting data.
In my code, I am able to validate only one row (either id or reg number), but if I am going to validate the two of them, it gives me an error, saying "Must declare the scalar variable #userid". I don't know if it is with my select that is wrong or something in my code.
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
con.Open();
SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = #userid AND RegNo = #reg", con);
SqlParameter param = new SqlParameter();
//SqlParameter param1 = new SqlParameter();
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
cmdd.Parameters.Add(param);
//cmdd.Parameters.Add(param1);
SqlDataReader reader = cmdd.ExecuteReader();
if (reader.HasRows)
{
MessageBox("User Id/Registry Number already exists");
}
else
{
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
SqlCommand cmd = new SqlCommand("qry", con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#regno", txtregNo.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
MessageBox("successfully saved!");
}
I am using C# with asp.net.
OK, so this isn't going to work:
SqlParameter param = new SqlParameter();
//SqlParameter param1 = new SqlParameter();
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
cmdd.Parameters.Add(param);
because you're reassigning the value of the same object. Change that to this:
cmdd.Parameters.AddWithValue("#userid", txtid.Text);
cmdd.Parameters.AddWithValue("#reg", txtregNo.Text);
this will add the parameters, two of them, to the SqlCommand object. Now, a little more advice, consider doing this:
using (SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"))
{
con.Open();
using (SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = #userid AND RegNo = #reg", con))
{
...
using (SqlDataReader reader = cmdd.ExecuteReader())
{
...
}
}
}
because right now you're not disposing those object properly.
You see, anything that implements IDisposable should be wrapped in a using statement to ensure the Dispose method is called on it.
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
You are only declaring 1 parameter and overwriting it for both ParameterName and Value.
As an aside, you should consider looking into some type of data access helper or ORM or something to save you the trouble of all that boilerplate SQL connection code.
You are also opening another connection inside of what should already be an open SQL connection.
You are using one instance of sql parameter and passing it two different values thus overriding the first one. Try it like this:
SqlParameter param1 = new SqlParameter("#userid", txtid.Text);
SqlParameter param2 = new SqlParameter("#reg", txtregNo.Text);
Your problem as per the error is that you are reassigning the parameter to #reg after you assign it to #userid.
Try this:
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
con.Open();
SqlCommand cmdd = new SqlCommand("select user_id from Profile where user_Id = #userid AND RegNo = #reg", con);
cmdd.Parameters.AddWithValue("#userid", txtid.Text);
cmdd.Parameters.AddWithValue("#reg", txtregNo.Text);
var id = cmdd.ExecuteReader() as string;
if (String.IsNullOrEmpty(id))
{
//Show error message and exit the method
}
else
{
//Add the row to the database if it didn't exist
}
EDIT:
I added some code to show how you could check if the userId exists in the table. Then you check against the user id itself instead of checking a reader object. Note, i am not at my dev computer right now so I did not compile this, you may have to do some tweaks but the idea is there.
I have a simple SQL Server stored procedure:
ALTER PROCEDURE GetRowCount
(
#count int=0 OUTPUT
)
AS
Select * from Emp where age>30;
SET #count=##ROWCOUNT;
RETURN
I am trying to access the output parameter in the following C# code:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "GetRowCount";
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
SqlDataReader reader=cmd.ExecuteReader();
int ans = (int)cmd.Parameters["#count"].Value;
Console.WriteLine(ans);
But on running the code, a NullReferenceException is being thrown at the second last line of the code. Where am I going wrong? Thanks in advance!
P.S. I am new to SQL Procedures, so I referred this article.
I'd suggest you put your SqlConnection and SqlCommand into using blocks so that their proper disposal is guaranteed.
Also, if I'm not mistaken, the output parameters are only available after you've completely read the resulting data set that's being returned.
Since you don't seem to need that at all - why not just use .ExecuteNonQuery() instead? Does that fix the problem?
using (SqlConnection con = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=answers;Integrated Security=True"))
using (SqlCommand cmd = new SqlCommand("dbo.GetRowCount", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#count", SqlDbType.Int));
cmd.Parameters["#count"].Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery(); // *** since you don't need the returned data - just call ExecuteNonQuery
int ans = (int)cmd.Parameters["#count"].Value;
con.Close();
Console.WriteLine(ans);
}
Also : since it seems you're only really interested in the row count - why not simplify your stored procedure to something like this:
ALTER PROCEDURE GetRowCount
AS
SELECT COUNT(*) FROM Emp WHERE age > 30;
and then use this snippet in your C# code:
con.Open();
object result = cmd.ExecuteScalar();
if(result != null)
{
int ans = Convert.ToInt32(result);
}
con.Close();
you have to specify that it is a stored procedure not a query
cmd.CommandType = CommandType.StoredProcedure;
Just use ExecuteNonQuery , you can't use ExecuteReader with out parameter in this case
cmd.ExecuteNonQuery();
Or if you want try with ExecuteScalar and ReturnValue
You should add
cmd.CommandType = CommandType.StoredProcedure
before calling it
I find the problem, its the connection string.
But now, in the code:
usuary = (string)cmd.Parameters["#USUARIO"].Value;
password = (string)cmd.Parameters["#CLAVE"].Value;
the compiler infomrs thats values are null...
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();
}
--Stored procedure
ALTER PROCEDURE [dbo].[Test]
#USERID varchar(25)
AS
BEGIN
SET NOCOUNT ON
IF NOT EXISTS Select * from Users where USERID = #USERID)
BEGIN
INSERT INTO Users (USERID,HOURS) Values(#USERID, 0);
END
I have this stored procedure in sql server 2005 and want to pass userid from a C# application. How can I do that. Many Thanks.
This topic is extensively covered in MSDN here. See the section entitled "Using Parameters with a SqlCommand and a Stored Procedure" for a nice sample:
static void GetSalesByCategory(string connectionString,
string categoryName)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SalesByCategory";
command.CommandType = CommandType.StoredProcedure;
// Add the input parameter and set its properties.
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter);
// Open the connection and execute the reader.
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
}