"Procedure or function expects parameter which was not supplied." - c#

I'm trying to execute a stored procedure and print the output, but when I run the below code I'm getting error like "Procedure or function 'SPInsertLocal' expects parameter '#RES', which was not supplied."
private void InsertPdtLocal(string code, string PON,string Qty)
{
string str = Properties.Settings.Default.conLocal;
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand("Execute SPInsertLocal #PON,#TCode,#Qty,#Type", con);
try
{
con.Open();
cmd.CommandTimeout = 150;
cmd.Parameters.AddWithValue("#PON", PON);
cmd.Parameters.AddWithValue("#Qty", Qty);
cmd.Parameters.AddWithValue("#TCode", code);
cmd.Parameters.AddWithValue("#Type", Globals.s_type);
SqlParameter output = new SqlParameter("#RES", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
con.Close();
int id = Convert.ToInt32(output.Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
What I'm doing wrong here?

SqlCommand cmd = new SqlCommand("Execute SPInsertLocal #PON,#TCode,#Qty,#Type,#RES", con);
I was not passing the parameter , fixed the issue

You can refactor the code as follows where the using statement is used for the auto management of connection closing and avoid hardcoding Execute statement in c# code which is a bad practice
private void InsertPdtLocal(string code, string PON,string Qty)
{
string str = Properties.Settings.Default.conLocal;
try
{
using (SqlConnection con = new SqlConnection(str))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.Parameters.AddWithValue("#PON", PON);
cmd.Parameters.AddWithValue("#Qty", Qty);
cmd.Parameters.AddWithValue("#TCode", code);
cmd.Parameters.AddWithValue("#Type", Globals.s_type);
var output = cmd.Parameters.Add("#RES" , SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int id = Convert.ToInt32(output.Value);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

Second connection object throwing error inside Transaction Scope

I'm developing a desktop application using VS.net and SQL Server. In one of the form, am using Transaction Scope. The code is as follows:-
//Constructor code
InitializeComponent();
ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbConSQLServerExp"].ConnectionString;
connectionString2 = System.Configuration.ConfigurationManager.ConnectionStrings["dbConSQLServerExp"].ConnectionString;
//Button save code
string sql1 = #"SELECT sub_id FROM TABLE1 WHERE c_id=#c_id";
try
{
using (TransactionScope scope = new TransactionScope())
{
using (SqlConnection con1 = new SqlConnection(connectionString))
{
con1.Open();
using (SqlCommand cmd1 = new SqlCommand(sql1, con1))
{
cmd1.Parameters.Add("#c_id", SqlDbType.Int).Value = clsId;
cmd1.CommandType = CommandType.Text;
using (SqlDataReader rdr1 = cmd1.ExecuteReader())
{
while (rdr1.Read())
{
string sql2 = #"INSERT INTO TABLE2(casm_cls_id,casm_ass_id,casm_subj_text,casm_subj_id,casm_subj_mm)
VALUES(#casm_cls_id,#casm_ass_id,#casm_subj_text,#casm_subj_id,#casm_subj_mm)";
using (SqlConnection con2 = new SqlConnection(connectionString2))
{
con2.Open();
using (SqlCommand cmd2 = new SqlCommand(sql2, con2))
{
cmd2.Parameters.Add("#casm_cls_id", SqlDbType.Int).Value = clsId;
cmd2.Parameters.Add("#casm_ass_id", SqlDbType.Int).Value = assId;
cmd2.Parameters.Add("#casm_subj_text", SqlDbType.VarChar, 20).Value = lvMapList.Items[row].SubItems[4].Text;
cmd2.Parameters.Add("#casm_subj_id", SqlDbType.Int).Value = Convert.ToInt32(rdr1["sub_id"].ToString());
cmd2.Parameters.Add("#casm_subj_mm", SqlDbType.Int).Value = Convert.ToInt32(txtMaxMarks.Text.Trim());
cmd2.CommandType = CommandType.Text;
cmd2.ExecuteNonQuery();
}
}
}
}
}
scope.Complete();
MessageBox.Show("Records added", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
catch (TransactionAbortedException tex)
{
MessageBox.Show("1-1--->>" + tex.Message);
}
catch (SqlException ex)
{
MessageBox.Show("1-2--->>" + ex.Message);
}
I'm encountering error at
con2.Open();
The error message simply says that the transaction has aborted.
Can anyone please explain what am I doing wrong or whats the correct way to do it?

How to add using statement in executescalar statement

How to add a using statement in following statement
this.OpenConnection();
SqlParameter[] SqlParameters = {new SqlParameter("#a",A)};
return Convert.ToLong( SqlHelper.ExecuteScalar((SqlConnection)DatabaseConnection, "StoredprocName",SqlParameters).ToString());
Here is an example From MSDN, hope this would help :
static public int AddProductCategory(string newName, string connString)
{
Int32 newProdID = 0;
string sql =
"INSERT INTO Production.ProductCategory (Name) VALUES (#Name); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("#Name", SqlDbType.VarChar);
cmd.Parameters["#name"].Value = newName;
try
{
conn.Open();
newProdID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return (int)newProdID;
}
More about SqlCommand.ExecuteScalar Method () : https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx

c# return out parameters from oracle function

I have textbox and on the leave event I am using oracle function to retrieve data for other textboxs so I made below code but i am getting no data found
private void TB_PRODUCT_DESC_Leave(object sender, EventArgs e)
{
string connstr = "Data Source=JDT; User Id=admin; password=admin;";
string cmdtxt = #"F_GET_PRODUCT_INFO"; //~ Returning CUSTOMER_ID from trigger in database ~//
using (OracleConnection conn = new OracleConnection(connstr))
using (OracleCommand cmd = new OracleCommand(cmdtxt, conn))
{
try
{
cmd.CommandText = cmdtxt;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("TB_PRODUCT_DESC", TB_PRODUCT_DESC.Text));
cmd.Parameters.Add(":V_PRODUCT_DESC", OracleDbType.Varchar2, ParameterDirection.ReturnValue);
conn.Open();
cmd.ExecuteReader();
TB_NOTES.Text = (cmd.Parameters[":V_PRODUCT_DESC"].Value).ToString();
MessageBox.Show(TB_NOTES.Text);
}
catch (Exception EX)
{ MessageBox.Show(EX.Message, "error msg", MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
function I am using below that return one varchar2 value
CREATE OR REPLACE FUNCTION F_GET_PRODUCT_INFO (P_PRODUCT_ID NUMBER)
RETURN VARCHAR2
IS
V_PRODUCT_DESC VARCHAR2 (200);
V_UNIT_PRICE NUMBER;
V_MEASUREMENT_UNIT VARCHAR2(32);
BEGIN
SELECT PRODUCT_DESC,
UNIT_PRICE,
MEASUREMENT_UNIT
INTO V_PRODUCT_DESC,
V_UNIT_PRICE,
V_MEASUREMENT_UNIT
FROM WAREHOUSE
WHERE PRODUCT_ID = P_PRODUCT_ID;
RETURN V_PRODUCT_DESC;
END F_GET_PRODUCT_INFO;
You need to specify a size for the varchar2:
OracelParameter prm = new OracleParameter(":V_PRODUCT_DESC");
prm.Direction = ParameterDirection.ReturnValue;
prm.DbType = OracleDbType.Varchar2;
prm.Size = 200;
cmd.Parameters.Add(prm);

Connect to SQL Server in C#

I'm a beginner programmer with C#. I'm trying to develop an application that it connects to a database and do the typical operations like insert, delete, update and get.
I'm getting a error with the database connection. I'm working with SQL Server 2012, where I have create a database called company.
This is my code:
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}
What is the error? I get an exception on this line:
command.Connection.Open();
Thanks in advance
SqlConnection con = new SqlConnection("Your Connection String Goes here");
You should assign connection to SqlCommand object like this
SqlCommand command = new SqlCommand();
command.Connection = con;
or
SqlCommand command = new SqlCommand("YourQuery",con);
Some Important Steps to Execute Command
1: Create SqlConnection Object and Assign a connection string to that object
SqlConnection con = new SqlConnection("Your Connection String Goes here");
or
SqlConnection con = new SqlConnection();
con.Connection = "Your Connection String Goes here";
2: Create SqlCommand Object and assing a command Text(Your Query) and connection string to that object
SqlCommand command = new SqlCommand("Select * from Products",con);
or
SqlCommand command = new SqlCommand();
command.Connection = con;
command.CommandText ="Select * from Products";
You can also specify CommandType
command.CommandType =CommandType.Text;
/* if you are executing storedprocedure CommandType Will be
=> CommandType.StoredProcedure; */
then You can Execute Command Like this
try
{
con.Open();
int TotalRowsAffected = command.ExecuteNonQuery();
}
catch(Exeception ex)
{
MessageBox.Show(ex.Message);
}
finaly
{
con.Close();
}
Just an FYI: An alternative to the try finally blocks, which ensure the database connection gets closed is to use the using statement such as:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
try
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (InvalidOperationException)
{
//log and/or rethrow or ignore
}
catch (SqlException)
{
//log and/or rethrow or ignore
}
catch (ArgumentException)
{
//log and/or rethrow or ignore
}
}
Refer to the MSDN documentation for the SqlCommand class here, https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx, and look up the ExecuteNonQuery() method, which is used to execute INSERT, UPDATE, and DELETE statements. Then look up ExecuteScalar() method that you can use to execute SELECT statements that return a single value. You can use ExecuteReader() to return a SqlDataReader for SELECT statements that return multiple columns.
not initialize sqlcommand connections, way for initialize this is :
command.Connection=con;
this is complete code for you :
namespace DAL
{
public class DAL
{
public const string CADENA_CONEXION = "Data Source=localhost;" +
"Initial Catalog=Company" +
"Integrated Security=false" +
"UID=root PWD=root";
public SqlConnection con;
public SqlCommand command;
public DAL()
{
con = new SqlConnection();
con.ConnectionString = CADENA_CONEXION;
}
public Boolean addEmployee(Employee emp)
{
try
{
/*String sqlInsertString = "INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES ("+e.firstName+","+ e.lastName+","+e.empCode+","+e.designation+")";*/
string sqlInsertString =
"INSERT INTO Employee (FirstName, LastName, ID, " +
"Designation) VALUES (#firstName, #lastName, #ID, #designation)";
command = new SqlCommand();
command.Connection=con;
command.Connection.Open();
command.CommandText = sqlInsertString;
SqlParameter firstNameparam = new SqlParameter("#firstName", emp.FirstName);
SqlParameter lastNameparam = new SqlParameter("#lastName", emp.LastName);
SqlParameter IDparam = new SqlParameter("#ID", emp.EmpCode);
SqlParameter designationParam = new SqlParameter("#designation", emp.Designation);
command.Parameters.AddRange(new SqlParameter[]{
firstNameparam,lastNameparam,IDparam,designationParam});
command.ExecuteNonQuery();
command.Connection.Close();
return true;
}
catch (Exception ex)
{
return false;
throw;
}
return true;
}
}

Local Database Insert query does nothing

I am trying to insert a row into the database. Below is my query:
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
string query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
using (SqlCommand command = new SqlCommand(query, conn))
{
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.AddWithValue("#x", insert[2]);
command.Parameters.AddWithValue("#y", insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
conn.Open();
try
{
command.ExecuteNonQuery();
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
conn.Close();
}
}
When I run it nothing happens (Also no SQL errors). What am I doing wrong? I am sorry if this is a stupid question, I am merely a beginner.
This should work (I have tested this with a select query that does work).
Have you tried storing the query on a stored procedure and calling it from C#? ... Thats actually easier than making the query via hard code inside the C# code ... Just create a stored procedure that does whatever you want it to do, then call it from C# and add the parameters. It should look something like this:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Your_Conection_String_s_Name"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "dbo.Your_Stored_Procedure";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Input_Param_1", SqlDbType.VarChar, 18).Value = "C#_Parameter1";
cmd.Parameters.Add("#Input_Param_2", SqlDbType.VarChar, 45).Value = "C#Parameter_2";
cmd.Parameters.Add("#Input_Param_3", SqlDbType.VarChar, 45).Value = "C#Parameter_3";
cmd.Parameters.Add("#Input_Param_4", SqlDbType.Text).Value = "C#Parameter_4";
cmd.Parameters.Add("#Input_Param_5", SqlDbType.VarChar, 45).Value = "C#Parameter_5";
cmd.Parameters.Add("#Output_Parameter_1", SqlDbType.VarChar, 250).Direction = ParameterDirection.Output;
cmd.Parameters.Add("#Output_Parameter_2", SqlDbType.DateTime).Direction = ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
"C#Output_Parameter_1" = "" + cmd.Parameters["#Output_Parameter_1"].Value;
"C#Output_Parameter_2" = "" + cmd.Parameters["#Output_Parameter_2"].Value;
Hope it helps.
My guess is that you have a type mismatch
If x, y are not int then substitute in the correct type
using (SqlConnection conn = new SqlConnection("Data Source = (LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Traindata.mdf;Integrated Security=True"))
{
using (SqlCommand command = SqlCommand.CreateCommand())
{
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
command.Query = "INSERT INTO dbo.Station (Naam, X, Y, Sporen) VALUES (#naam, #x, #y, #sporen)";
command.Parameters.AddWithValue("#naam", insert[1]);
command.Parameters.Add("#x", SqlDbType.Int);
command.Parameters["#x"].Value = Int32.Parse(insert[2]);
command.Parameters.Add("#y", SqlDbType.Int);
command.Parameters["#y"].Value = Int32.Parse(insert[3]);
command.Parameters.AddWithValue("#sporen", insert[4]);
rowsRet = command.ExecuteNonQuery();
Console.WriteLine(rowsRet.ToString());
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
// op claims the insert is gone the next time the programs is run
try
{
conn.Open();
command.Query = "select count(*) from dbo.Station";
Int32 rowsRet = (Int32)command.ExecuteScalar();
Console.WriteLine(rowsRet.ToString());
}
catch (SqlException exc)
{
Console.WriteLine("Error to save on database");
Console.WriteLine(exc.Message);
}
finally
{
conn.Close();
}
}
}

Categories

Resources