Adding more number of parameters to sqlparameter class - c#

I have to call a stored procedure but i am having more number of parameters is there any simple way to do this? or simply adding every parameter to sqlparameter class?? like below
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;

Be aware that Paramters.Add has an overload that takes in a string and a DbType, so you don't have to call the Parameter constructor. You could replace the line you are currently using to add a new parameter:
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar)).Value = TextBox1.Text;
with the following shorter (but functionally equivalent) line:
command.Parameters.Add("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
If you want to add more parameters, you would simply add them to the Parameters property of your command, like so:
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
command.Parameters.Add("#Lastname", SqlDbType.NVarChar).Value = TextBox2.Text;
Aside from that, have you tried using Parameters.AddWithValue? You can use this if the data type of your column maps to the type of your value in C#. You can find a mapping of C# to SQL Server data typse here.
You would use it like so:
// Assume your sproc has a parameter named #Age that is a SqlInt32 type
int age = 5;
// Since age is a C# int (Int32), AddWithValue will automatically set
// the DbType of our new paramter to SqlInt32.
command.Parameters.AddWithValue("#Age", 5);
If you need to specify the SqlDbType, AddWithValue returns the parameter you just added, so it's as simple as adding an extra statement to set the DbType property at the end, although at this point, you're better off just using the original .Add function and setting the value.
command.Parameters.AddWithValue("#Firstname", TextBox1.Text).DbType = SqlDbType.NVarChar;

Use Array of type SqlParameter and insert that into SqlCommand
SqlCommand Comm = new SqlCommand("Command text", new SqlConnection("Connection String");
SqlParameter[] param = {new SqlParameter("#Name","Value"),
new SqlParameter("#Name","Value"),
........
};
Comm.Parameters.AddRange(param);

Just call the command.Parameters.Add method multiple times:
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Firstname", SqlDbType.NVarChar, 100).Value = TextBox1.Text;
command.Parameters.Add("#Lastname", SqlDbType.NVarChar, 100).Value = TextBox2.Text;
command.Parameters.Add("#City", SqlDbType.NVarChar, 100).Value = TextBox3.Text;
command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox4.Text);
....... and so on .....

You may use like it
return new SqlParameter[]
{
new SqlParameter("#Firstname", SqlDbType.VarChar)
{
Value = Firstname.Text
},
new SqlParameter("#Lastname", SqlDbType.VarChar)
{
Value = Lastname.Text
},
};

You can use dapper-dot-net
sample code:
var dog = connection.Query<Dog>("select Age = #Age, Id = #Id", new { Age = (int?)null, Id = guid });
Insert example:
connection.Execute(#"insert MyTable(colA, colB) values (#a, #b)",
new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } }
).IsEqualTo(3); // 3 rows inserted: "1,1", "2,2" and "3,3"

The command.Parameters.Add is deprecated. Rather use command.Parameters.AddWithValue .
For this, you would call it many times for each parameter.

// Mention size of the nvarchar column , here i give 500 , you can use its length for #Firstname as you mention in database according to your database
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar,500).Value = TextBox1.Text;

Related

C# update stored procedure not making changes to database

I have looked at similar topics with no luck, it looks (to me) like im doing things correctly but the database is just not being updated.
My function, as below, has the parameter values of 1, "Connor Smith", 5, "New" respectively
[HttpPost, ValidateAntiForgeryToken]
public ActionResult UpdateDevelopmentRequest(int changeID, string evaluator, int priority, string status)
{
SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.UpdateDevRequest, Conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#changeID", SqlDbType.Int).Value = changeID;
cmd.Parameters.Add("#evaluator", SqlDbType.NVarChar, 30).Value = evaluator;
cmd.Parameters.Add("#priority", SqlDbType.Int).Value = priority;
cmd.Parameters.Add("#status", SqlDbType.NVarChar, 15).Value = status;
//cmd.Parameters.AddWithValue("#changeID", changeID);
//cmd.Parameters.AddWithValue("#evaluator", evaluator);
//cmd.Parameters.AddWithValue("#priority", priority);
//cmd.Parameters.AddWithValue("#status", status);
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
return RedirectToAction("DevelopmentRequests");
}
My stored procedure is as below
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[sp_UpdateDevRequests]
#changeID INT,
#evaluator NVARCHAR(30),
#priority INT,
#status NVARCHAR(15)
AS
UPDATE it_ChangeRequest
SET it_ChangeRequest.Evaluator = #evaluator,
it_ChangeRequest.Status = #status,
it_ChangeRequest.Priority = #priority
WHERE ChangeID = #changeID
Aside from the code and stored procedure as shown, I have tried to add
int result = cmd.ExecuteNonQuery();
which returned a 1 when values were correct and a 0 when they were incorrect (I am only expecting 1 row to be changed). I have also ran the query separately, hardcoding the values in e.g Declare #changeID int = 1 and the query worked fine with this method too.
I have been stumped on this all morning and would appreciate some help
e: I also tried setting the stored procedure to just priority = 2 instead of priority = #priority to ensure it was pointed and updating the expected DB and all worked as expected when doing that
Please try changing your POST action as below by specifying ParameterDirection:
[HttpPost, ValidateAntiForgeryToken]
public ActionResult UpdateDevelopmentRequest(int changeID, string evaluator, int priority, string status)
{
using (var conn = new SqlConnection(<your_connection_string_goes_here>))
using (SqlCommand cmd = new SqlCommand(StoredProcedures.DevRequests.UpdateDevRequest, Conn))
{
cmd.CommandType = CommandType.StoredProcedure;
/*
cmd.Parameters.Add("#changeID", SqlDbType.Int).Value = changeID;
cmd.Parameters.Add("#evaluator", SqlDbType.NVarChar, 30).Value = evaluator;
cmd.Parameters.Add("#priority", SqlDbType.Int).Value = priority;
cmd.Parameters.Add("#status", SqlDbType.NVarChar, 15).Value = status;
*/
var param1 = cmd.Parameters.AddWithValue("#changeID", changeID);
cmd.Parameters["#changeID"].Direction = ParameterDirection.Input
param1.SqlDbType = SqlDbType.Int
var param2 = cmd.Parameters.AddWithValue("#evaluator", evaluator);
cmd.Parameters["#evaluator"].Direction = ParameterDirection.Input
param2.SqlDbType = SqlDbType.NVarChar
var param3 = cmd.Parameters.AddWithValue("#priority", priority);
cmd.Parameters["#priority"].Direction = ParameterDirection.Input
param3.SqlDbType = SqlDbType.Int
var param4 = cmd.Parameters.AddWithValue("#status", status);
cmd.Parameters["#status"].Direction = ParameterDirection.Input
param4.SqlDbType = SqlDbType.NVarChar
Conn.Open();
// If you want you can specify the Timeout as below
// cmd.CommandTimeout = 300;
cmd.ExecuteNonQuery();
Conn.Close();
}
return RedirectToAction("DevelopmentRequests");
}

error with addwithvalue sql parameter

I've been advised to replace my code with SqlParameter to avoid SQL injection as a security issue but with my limited understanding. I tried implementing it but I'm faced with an error:
Must Declare Scalar Variable
I've tried the other suggestions of other threads about implementing a new parameter for every insertion instead of replacing the value of parameter for every entry.
String query = "INSERT INTO EmpInfo(EmpYear, EmpStatus, LName, FName, JobTitle, EmpPay, EmpDoB, EmpSex, EmpAddr, EmpCity, EmpState, EmpZIP, EmpCountry, EmpEAddr, EmpTelNo, EmpMobileNo, EmpDate) " +
"VALUES('"+EmpYear+"', #EmpStatus, #LName, #FName, #JobTitle, #EmpPay, #EmpDoB, #EmpSex, #EmpAddr, #EmpCity, #EmpState, #EmpZIP, #EmpCountry, #EmpEAddr, #EmpTelNo, #EmpMobileNo, getdate())";
String query2 = "INSERT INTO AccountInfo(LName, FName, EmpTemplate, AccountType, EmpStatus, EmpDate) " +
"VALUES (#LName, #FName, #EmpTemplate, #AccountType, #EmpStatus, GetDate())";
using (SqlConnection connection = new SqlConnection("Data Source=RB-DESKTOP;Initial Catalog=TimeDB;Persist Security Info=True;User ID=sa;Password=bautista7"))
{
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "SELECT MAX(EmpID) FROM EmpInfo";
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Close();
SqlCommand command = new SqlCommand(query, cmd.Connection);
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpYear", Value = EmpYear });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpStatus", Value = "Active" });
command.Parameters.Add(new SqlParameter() { ParameterName = "#LName", Value = regLname_text.Text });
command.Parameters.Add(new SqlParameter() { ParameterName = "#FName", Value = regFname_text.Text });
command.Parameters.Add(new SqlParameter() { ParameterName = "#JobTitle", Value = "NULL" });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpPay", Value = PayType_cb.SelectedItem.ToString() });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpDoB", Value = regDob_dtp.Value.Date });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpSex", Value = gender });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpAddr", Value = regAddr_text.Text });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpCity", Value = regCity_text.Text });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpState", Value = regState_text.Text });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpZIP", Value = regZip_text.Text });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpCountry", Value = regCountry_text.Text });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpEAddr", Value = regEmail_text.Text });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpTelNo", Value = regTel_text.Text });
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpMobileNo", Value = regMob_text.Text });
command.ExecuteNonQuery();
command.Parameters.Clear();
SqlCommand command2 = new SqlCommand(query2, cmd.Connection);
command.Parameters.AddWithValue("#LName", regLname_text.Text);
command.Parameters.AddWithValue("#FName", regFname_text.Text);
command.Parameters.AddWithValue("#EmpTemplate", template);
command.Parameters.AddWithValue("#AccountType", AcctType_cb.SelectedItem.ToString());
command.Parameters.AddWithValue("#EmpStatus", "Active");
command.ExecuteNonQuery();
command.Parameters.Clear();
You are using the command variable twice instead of command2 after you create command2. You get the error because you cleared command of all parameters, then add parameters (which do not match the existing query) and then execute ExecuteNonQuery which then throws the error.
Change 2nd execution statement / command like so, notice that after the creation of command2 it is now also used instead of reusing command.
SqlCommand command2 = new SqlCommand(query2, cmd.Connection);
command2.Parameters.AddWithValue("#LName", regLname_text.Text);
command2.Parameters.AddWithValue("#FName", regFname_text.Text);
command2.Parameters.AddWithValue("#EmpTemplate", template);
command2.Parameters.AddWithValue("#AccountType", AcctType_cb.SelectedItem.ToString());
command2.Parameters.AddWithValue("#EmpStatus", "Active");
var numberOfRecordsInserted = command2.ExecuteNonQuery();
// value of numberOfRecordsInserted should be 1
Also when you are done using a SqlCommand you can dispose of it, there is no need to call SqlCommand.Parameters.Clear() unless you plan on reusing the exact same SqlCommand instance which you are not (at least not in the posted code).
I think you should try simplify your logic first. I found several weird things.
query has "VALUES('"+EmpYear+"', I think you want #EmpYear because you also have
command.Parameters.Add(new SqlParameter() { ParameterName = "#EmpYear", Value = EmpYear });
Additionally
SqlCommand cmd = new SqlCommand(query, connection);
//^^^ here you use insert query
cmd.Connection = conn;
conn.Open();
cmd.CommandText = "SELECT MAX(EmpID) FROM EmpInfo"; // But here you change it for a SELECT?
// Then you execeute a DataReader but you close it before save the result.
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Close();
//Then create the insert command again
SqlCommand commad = new SqlCommand(query, cmd.Connection);
....
// clear command, I guess you want reuse it
command.Parameters.Clear();
// now create command 2 is OK
SqlCommand command2 = new SqlCommand(query2, cmd.Connection);
// ^^^ second insert query
// but add parameteres to command NOT OK
command.Parameters.AddWithValue("#LName", regLname_text.Text);

Trying to update db - no errors but no update either

I have a problem in trying to update a database using SQL update command and DataGridView.
Int16 ID, An;
// update db using sql command, the code does not update the database
SqlCommand cmd = new SqlCommand("update filme set ID = #ID, Nume = #Nume, Gen = #Gen, Descriere = #Descriere, Actori = #Actori, An = #An, Rating = #Rating, Pret = #Pret where ID = #ID");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#ID", SqlDbType.SmallInt).Value = Int16.TryParse("#ID", out ID);
cmd.Parameters.AddWithValue("#Nume", SqlDbType.NVarChar).Value = "#Nume";
cmd.Parameters.AddWithValue("#Gen",SqlDbType.NVarChar).Value = "#Gen";
cmd.Parameters.AddWithValue("#Descriere", SqlDbType.NVarChar).Value = "#Descriere";
cmd.Parameters.AddWithValue("#Actori", SqlDbType.NVarChar).Value = "#Actori";
cmd.Parameters.AddWithValue("#An", SqlDbType.SmallInt).Value = Int16.TryParse("#An", out An) ;
cmd.Parameters.AddWithValue("#Rating", SqlDbType.NVarChar).Value = "#Rating";
cmd.Parameters.AddWithValue("#Pret",SqlDbType.Money).Value = "#Pret";
connection.Open();
cmd.ExecuteNonQuery();
This code does not produce any errors, but does not update the database. Something is wrong but I don't know what.
I use Visual Studio Community and SQL Server 2012. The information from database are displayed in a DataGridView.
Thank you !
You set the #ID parameter with this line
Int16.TryParse("#ID", out ID);
what do you expect to be the result of converting the string #ID to an integer?
And Int16.TryParse returns a boolean, true if the conversion succeed, false otherwise.
Then you use
cmd.Parameters.AddWithValue("#ID", SqlDbType.SmallInt).Value = .....
The second parameter of AddWithValue is the Value to give to the parameter, not the type.
The remainder follows the same pattern and so this code will never work.
As an example, you should write:
SqlCommand cmd = new SqlCommand(#"update filme set Nume = #Nume, Gen = #Gen,
Descriere = #Descriere, Actori = #Actori,
An = #An, Rating = #Rating, Pret = #Pret
where ID = #ID", connection);
cmd.Parameters.Add(new SqlParameter
{ ParameterName = #Nume,
SqlDbType = SqlDbType.Int,
Value = Convert.ToInt32(someTextBox.Text) // Or some datagridview cell...
};
...and so on for the other parameters...
Notice also that I have removed the part about SET ID = #ID because this makes no sense. If you use the ID field as your search condition then updating it with the value that you are searching for could only lead, in the best situation, at no change for the ID field and in the worst situation to changing a different record from the intended one.
The way you use the .AddWithValue is all wrong .....
You have
cmd.Parameters.AddWithValue("#ID", SqlDbType.SmallInt).Value = Int16.TryParse("#ID", out ID);
but you're really defining the parameter name and datatype (which is a good thing!) and then you use the .Value = ... to handle the value assignment.
These lines of code should really be:
cmd.Parameters.Add("#ID", SqlDbType.SmallInt).Value = Int16.TryParse("#ID", out ID);
I bet using this approach, your code will work just fine.

Another SQL parameter - UPDATE statement

I'm not seeing why my update statement isn't actually updating. Here is what I have:
private void submit_button_Click(object sender, EventArgs e)
{
string insert = insertbox.Text;
SqlParameter param2 = new SqlParameter("#param2", SqlDbType.Text);
param2.Value = insert;
var connlink = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Microsoft SQL Server\\MSSQL.2\\MSSQL\\Data\\Inserts.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
var cmd1 = new SqlCommand(#"SELECT qty_onhand FROM [insert] WHERE (Name LIKE #param2)", connlink);
connlink.Open();
cmd1.Parameters.Add(param2);
var onhand = Convert.ToInt16(cmd1.ExecuteScalar());
// The param2 in the statement passes fine and returns the value into "onhand".
// Below, the parameters don't seem to be passed. There is no error but the record isn't updated.
int new_onhand = Convert.ToInt16(qtybox1.Text);
Convert.ToInt16(onhand);
new_onhand = onhand - new_onhand;
SqlParameter param1 = new SqlParameter("#param1", SqlDbType.SmallInt);
param1.Value = new_onhand;
SqlParameter param3 = new SqlParameter("#param3", SqlDbType.Text);
param3.Value = param2.ToString();
var cmd = new SqlCommand(#"UPDATE [insert] SET qty_onhand = #param1 WHERE (Name LIKE #param3)", connlink);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param3);
cmd.ExecuteNonQuery();
connlink.Close();
}
I'm not sure of the difference of why one works and the other doesn't.
you set the value of param3 by calling ToString on param2: param3.Value = param2.ToString();
Calling ToString on a SqlParameter returns the parameter name. In our case, it returns "#param2" as a string, and not the value of it. Try using param2.Value.
Or actually to insert, since you wrote param2.Value = insert;.
The lines below looks incorrect to me because param2 is of type SqlParameter and you using param2.ToString() as value for param3.value
SqlParameter param3 = new SqlParameter("#param3", SqlDbType.Text);
**param3.Value = param2.ToString();**

How to run the stored procedure that has OUTPUT parameter from C#?

I have a stored procedure with an output parameter. How do I read this value using C# code?
I assume you use ADO.NET? If so, the SqlParameter class has the property "Direction". Set direction to output and after the query has executed you read the value from that parameter.
Something like this:
using (SqlCommand cmd = new SqlCommand("MyStoredProcedure", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm = new SqlParameter("#pkid", SqlDbType.Int);
parm.Value = 1;
parm.Direction = ParameterDirection.Input;
cmd.Parameters.Add(parm);
SqlParameter parm2 = new SqlParameter("#ProductName", SqlDbType.VarChar);
parm2.Size = 50;
parm2.Direction = ParameterDirection.Output; // This is important!
cmd.Parameters.Add(parm2);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}

Categories

Resources