-1

how to pass a parameter to sqlParam

_id=23
SqlClient.Main.CreateCommand("select X from TAB where ID= @id", new SqlParam("id", K_{0}), _id)).ExecScalar<int>();

I have a variable that should be need to pass in SqlParam. parameters id="K_23" or "K_3131". now sql does't see this parameter. How it correctly make!?

MatBailie
  • 83,401
  • 18
  • 103
  • 137
Nastya
  • 101
  • 1
  • 1
  • 8
  • What do you want to pass to the command? 23? This would be `new SqlParam("id", 23)` ... what is K_23 oder K_3131? Maybe you can elaborate your question. – Hinek Nov 22 '18 at 12:52
  • its my parameter like new SqlParam("id", K_23), where K_ = constant and 23 value (variable value which I find in the database) – Nastya Nov 22 '18 at 14:23

2 Answers2

1

The pattern generally runs more like this:

SqlCommand cmd = new SqlCommand("SELECT * FROM table WHERE column = @val", conn);
cmd.Parameters.AddWithValue("@val", 123);
cmd.Parameters.Add(new...);

But please read these:

SqlCommand Parameters Add vs. AddWithValue

And in particular these, if you're thinking of using AddWithValue heavily:

https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

http://www.dbdelta.com/addwithvalue-is-evil/

Actually, for the most part you shouldn't really be writing code like this at all any more for the simple stuff* - there are plenty of good data access libraries/methodologies (EF, nHibernate, Dapper, DataTables) that mean that slinging SQL-inside-strings into your event handlers etc is just not necessary and is primitive/unproductive. Noone spends time writing code to raw lines on screen to represent a button; they just add a Button to the page/form. There's no need to get that low level with databases either; use a data access framework

*select blah from blah where blah is undeniably simple stuff. Everyone should be handing those kinds of queries off to an ORM library, and i'm completely appalled that use of SqlCommand/DataReader etc is still taught/advocated for this level of query complexity

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
0

Based on your answer to my comment, I think you are looking for this:

private int _id = 23
// ...
var idParam = new SqlParam("id", string.Format("K_{0}", _id))
SqlClient.Main.CreateCommand("... where ID=@id", idParam).ExecScalar<int>();

string.Format("K_{0}", _id) creates the string "K_23". Another way in the newer C# versions would be $"K_{_id}".

new SqlParam("id", "K_23") creates a string parameter with the value "K_23".

Your command then filters by ID='K_23'.

Is that what you are trying to achive? Or is K_23 a field in your database and you want to check if the field ID has the same value as the field K_23?

Hinek
  • 9,519
  • 12
  • 52
  • 74