C# OracleCommand SQL Call Procedure with Params - c#

I would like to call a (Oracle) Procedure from C#. My Code:
try
{
OracleConnection myOracleConnection = new OracleConnection(connectionString);
myOracleConnection.Open();
OracleCommand command = myOracleConnection.CreateCommand();
command.CommandText = String.Format("BEGIN MISSINGTABLES ('{0}', '{1}'); END;", "PEKA_ERP_001", "ASE_ERP_001");
command.CommandType = System.Data.CommandType.Text;
command.ExecuteNonQuery();
myOracleConnection.Close();
}
catch (OracleException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
The Procedure:
CREATE OR REPLACE PROCEDURE MISSINGTABLES (S1 IN VARCHAR2, S2 IN VARCHAR2) AS
BEGIN [...]
on command.ExecuteNonQuery(); I get an Exception..:
PL/SQL: Statement ignored
OracleException Unhandled
What I'm doing wrong?

Did it :)
OracleCommand command = myOracleConnection.CreateCommand();
command.CommandText = "MISSINGTABLES";
command.Parameters.Add(new OracleParameter("S1", OracleType.VarChar)).Value = "PEKA_ERP_001";
command.Parameters.Add(new OracleParameter("S2", OracleType.VarChar)).Value = "ASE_ERP_001";
command.CommandType = System.Data.CommandType.StoredProcedure;
command.ExecuteNonQuery();
myOracleConnection.Close();

Related

C# update and set of database (datediff) don't work when in C# but works if in SQL Server

I have searched for solutions but I can't find one; please help.
I have this code fragment in C#:
using (SqlCommand command = new SqlCommand())
{
command.Connection = openCon;
command.CommandType = CommandType.Text;
command.CommandText = "update logRecords set totalHours = DATEDIFF(HOUR,timeIn,timeOut)";
try
{
openCon.Open();
int recordsAffected = command.ExecuteNonQuery();
MessageBox.Show("Records affected: " + recordsAffected);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
openCon.Close();
GetLogData();
}
}
but it doesn't work. It didn't show the message box in the try block neither the one in the catch block.
Thanks for helping :D
You can access query with parameters, hope this help:
using(var openCon = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand())
{
command.Connection = openCon;
command.CommandType = CommandType.Text;
command.CommandText = "update logRecords set totalHours = DATEDIFF(HOUR,#timeIn,#timeOut)";
try
{
openCon.Open();
command.Parameters.AddWithValue("#timeIN", timeIn);
command.Parameters.AddWithValue("#timeOut", timeOut);
int recordsAffected = command.ExecuteNonQuery();
MessageBox.Show("Records affected: " + recordsAffected);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
GetLogData();
}
First of all I will create Stored procedure and I will update any of my table through procedure.
So, Basic SP will be like below, and I will run it in a Database(SQL).
CREATE PROCEDURE Set_LogRecords_TotalHours
-- Add the parameters for the stored procedure here
#timeIn datetime,
#timeOut datetime
AS
BEGIN
SET NOCOUNT ON;
-- Insert statements for procedure here
UPDATE LogRecords
SET TotalHours = DATEDIFF(HOUR, #timeIn, #timeOut)
-- returns number of rows
SELECT ##ROWCOUNT
END
GO
Now, I will Move to code side.
I will Create a Generic method to call All of mine Stored procedures, see below.
public static DataSet GetRecordWithExtendedTimeOut(string SPName, params SqlParameter[] SqlPrms)
{
DataSet ds = new DataSet();
try
{
//here give reference of your connection and that is "openCon"
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(SPName, conn))
{
command.Parameters.AddRange(SqlPrms);
command.CommandTimeout = 0;
conn.Open();
command.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command))
{
try
{
dataAdapter.SelectCommand = command;
dataAdapter.Fill(ds);
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
}
}
}
catch (Exception ex)
{
//Handle Errror
}
return ds;
}
Now at last, call this method from wherever you need to access database.
Over here is the example of calling generic method.
//Add all the parameter that you want to pass to SP, here we have 2 and they are in DAteTime Formate
SqlParameter[] parameters =
{
new SqlParameter { ParameterName = "#timeIn", Value = ValueOf_TimeIN_DateTIME }
new SqlParameter { ParameterName = "#timeOut", Value = ValueOf_TimeOUT__DateTIME}
};
DataSet ds = DAL.GetRecordWithExtendedTimeOut("Set_LogRecords_TotalHours", parameters);
if (ds != null && ds.Tables.Count >= 1 && ds.Tables[0].Rows.Count >= 1)
{
//Debugg ds and you will see the number of records that affected in last update
}

Detect if stored proc delete ran

If I calling a stored proc how do i detect that it has completed succesfully on the server as right now im just doing a try catch which is not the best way of doing this.
public bool deleteTeam(Guid teamId)
{
try
{
string cs = ConfigurationManager.ConnectionStrings["uniteCms"].ConnectionString;
SqlConnection myConnection = new SqlConnection(cs.ToString());
// the stored procedure
SqlCommand cmd = new SqlCommand(
"proc_unitecms_deleteTeam", myConnection);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(
new SqlParameter("#ID", teamId));
return true;
} catch(Exception ex)
{
return false;
}
}
You can return the affected rows number and return -1 in case of catch a exception .
You forget the ExecuteNonQuery.
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
Int32 rowsAffected;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
sqlConnection1.Close();

Inserting an E notation double into a decimal column

I have a number in C# which is double longitude =1.041970849797e-05.
When I try to insert it into a decimal(9,6) column, I get the error message:
Error converting data type nvarchar to numeric
How do I correctly save the above as a decimal?
C# Application Code:
static void Main(string[] args)
{
double lat=1.041970849797e-05;
insertRecs(lat);
}
private static void insertRecs(double latitude)
{
Int32 rowsAffected = 0;
string connectionString = GetConnectionString();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("dbo.usp_temp", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 90;
try
{
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ep)
{
Console.WriteLine("Exception in Insertrecords ");
Console.WriteLine(ep.Message);
}
}
}
SQL Stored Procedure:
create PROCEDURE [dbo].[usp_temp]
--The parameters for the stored procedure
#latitude decimal(9,6)
AS
BEGIN
insert into temptest(latitude) values(#latitude);
END
Looking at the sample of code you gave us you don't actually map the latitude variable when running the Stored Procedure.
You would need to add a couple of lines like so:
SqlParameter param = cmd.Parameters.Add("#latitude", SqlDbType.Decimal);
param.Direction = ParameterDirection.Input;
param.Value = latitude;
And edited into your code:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("dbo.usp_temp", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 90;
// Map the parameters into the Stored Procedure
SqlParameter param = cmd.Parameters.Add("#latitude", SqlDbType.Decimal);
param.Direction = ParameterDirection.Input;
param.Value = latitude;
try
{
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception ep)
{
Console.WriteLine("Exception in Insertrecords ");
Console.WriteLine(ep.Message);
}
}

Exception returned when inserting into table through ASP.NET 3.5 C# method

I have a method that sends two variables, an int and a delimited string, to an SQL Server proc.
Variable values (copied from debugger):
detailId: 5
fileNames: "recruiter.txt|cert.pdf"
The method:
public void InsertFiles(int detailId, string fileNames)
{
ConnectionStringSettings connString = ConfigurationManager.ConnectionStrings["PRADB"];
using (SqlConnection conn = new SqlConnection(connString.ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "dbo.InsertFiles";
cmd.Parameters.AddWithValue("#detailId", detailId);
cmd.Parameters.AddWithValue("#fileNames", fileNames);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
string exc = ex.ToString();
}
finally
{
conn.Close();
}
}
}
Here is the proc:
ALTER PROCEDURE [dbo].[InsertFiles]
#detailId int,
#fileNames varchar(max)
AS
BEGIN
SET NOCOUNT ON;
insert into [dbo].[PRA_Files] (detailId, fileNames)
values (#detailId, #fileNames)
END
The exception received when debugging:
{"Incorrect syntax near 'dbo'."}
Yet when I execute from the proc:
exec [dbo].[InsertFiles] 5, "recruiter.txt|cert.pdf"
It works fine. There error isn't code side as it is being caught in the catch block of the method above. I'm stumped.
You need to specify that the command is a stored procedure:
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "dbo.InsertFiles";
cmd.Parameters.AddWithValue("#detailId", detailId);
cmd.Parameters.AddWithValue("#fileNames", fileNames);
cmd.CommandType = CommandType.StoredProcedure;

How to acces a flag set in sql server into business logic

public int InsertCompanyDetailsInformation(int companyId, int bankId, int accountNo, string accountType)
{
int rowsAffected = -1;
int returnValue;
try
{
SqlConnection con = DBProvider.GetDbConnection();
using (con)
{
con.Open();
SqlCommand objCmd = new SqlCommand("dbo.sp_InsertCompanyDetailsInformation", con);
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.AddWithValue("#companyId", companyId);
objCmd.Parameters.AddWithValue("#bankId", bankId);
objCmd.Parameters.AddWithValue("#accountNo", accountNo);
objCmd.Parameters.AddWithValue("#accountType", accountType);
rowsAffected = objCmd.ExecuteNonQuery();
SqlParameter sqlParam = objCmd.Parameters.Add("#insert_flag", SqlDbType.Int);
objCmd.Parameters["#insert_flag"].Direction = ParameterDirection.ReturnValue;
returnValue = int.Parse(objCmd.Parameters["#insert_flag"].Value.ToString());
con.Close();
}
}
catch (Exception ex)
{
throw ex;
}
return rowsAffected;
}
and stored procedure
USE [SGTime_Development]
GO
/****** Object: StoredProcedure [dbo].[sp_InsertCompanyDetailsInformation] Script Date: 01/04/2011 14:31:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_InsertCompanyDetailsInformation]
(
#companyId int,
#bankId int,
#accountNo int,
#accountType varchar(50))
AS
BEGIN
SET NOCOUNT ON;
declare #insert_flag int;
if not exists(select AccountNo from [Company_Account_Details] where AccountNo=#accountNo)
begin
INSERT INTO [Company_Account_Details]
( Company_Id,
BankID,
AccountNo,
AccountType)
values
(#companyId,
#bankId,
#accountNo,
#accountType)
set #insert_flag=1;
END
else
begin
set #insert_flag=-1;
end
return #insert_flag;
end
I am getting error in the code i want return returnValue in InsertCompanyDetailsInformation Please help how we can return returnValue
You need to add parameter for return value before you execute the command. So you need to change code as below:
...
objCmd.Parameters.AddWithValue("#accountType", accountType);
// Add parameter for return value
SqlParameter sqlParam = objCmd.Parameters.Add("#insert_flag", SqlDbType.Int);
objCmd.Parameters["#insert_flag"].Direction = ParameterDirection.ReturnValue;
// now execute the command
rowsAffected = objCmd.ExecuteNonQuery();
// you should able to get return value now
returnValue = int.Parse(objCmd.Parameters["#insert_flag"].Value.ToString());
...
public int InsertCompanyDetailsInformation(int companyId, int bankId, int accountNo, string accountType)
{
int rowsAffected = -1;
int returnValue;
try
{
SqlConnection con = DBProvider.GetDbConnection();
using (con)
{
con.Open();
SqlCommand objCmd = new SqlCommand("dbo.sp_InsertCompanyDetailsInformation", con);
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.AddWithValue("#companyId", companyId);
objCmd.Parameters.AddWithValue("#bankId", bankId);
objCmd.Parameters.AddWithValue("#accountNo", accountNo);
objCmd.Parameters.AddWithValue("#accountType", accountType);
rowsAffected = objCmd.ExecuteNonQuery();
SqlParameter sqlParam = objCmd.Parameters.Add("#insert_flag", SqlDbType.Int);
sqlParam.Direction = ParameterDirection.ReturnValue;
// now execute the command
objCmd.Parameters.Add(sqlParam);
con.Open();
rowsAffected = objCmd.ExecuteNonQuery();
con.Close();
returnvalue = (int)objCmd.Parameters["insert_flag"].Value;
}
}
catch (Exception ex)
{
throw ex;
}
return rowsAffected;
}
}

Categories