passing columnname with a parameter SQLcommand - c#

I've been googling something I dont really cant understand.
In short my problem is this;
When using this;
String sYear2 = "2020";
string query = #"Select decJan from Stats where intRecnum = (select intRecnum from Stats where intAr = #year)";
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#year", sYear2);
The result is returning "111" (which is correct vaule of column decJan the year 2020.
But when trying this;
String sYear2 = "2020";
String sColumn2 = "decJan";
string query = #"Select " + #column + #" from tbFuGraddagar where intRecnum = (select intRecnum from tbfuGraddagar where intAr = #year)";
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#year", sYear2);
cmd.Parameters.AddWithValue("#column", sColumn2);
I recieve "decJan" as result.
When googling all I have found that its not possible without dynamic SQL or that is bad design.
But I fail to understand what the diffrence is...all I want is to change the static code with a value similar to #year-parameter. the "interpretation" shouldn't care about the validation of SQL-syntax, it's just a matter och string-manipulation.
Or is it just me beeing a bad C#-coder?

Probably addwithvalue method is not valid for adding dynamic column names in select statements. I think you should use c# 8.0 feature, string interpolation to solve this problem.  You can add column names with string interpolation. Can you try this approach :
String sYear2 = "2020";
string deccan = "decJan";
string query = $(Select {decJan} from Stats where intRecnum = (select intRecnum from Stats where intAr = #year)
query = #query;
var cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#year", sYear2);

Related

Query working in mysql but not from c# code

I am having c# code like this:
using (MySqlConnection con = new MySqlConnection(AR.ConnectionString))
{
con.Open();
using (MySqlCommand cmd = new MySqlCommand(#"SELECT PORUDZBINAID, USERID, BRDOKKOM, DATUM,
STATUS, MAGACINID, PPID, INTERNIKOMENTAR, REFERENT_OBRADE, NACIN_PLACANJA, TAG FROM
PORUDZBINA WHERE TAG LIKE '%#MOB%'", con))
{
cmd.Parameters.AddWithValue("#MOB", Mobilni);
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
list.Add(new Porudzbina()
{
PorudzbinaID = Convert.ToInt32(dr[0]),
UserID = Convert.ToInt32(dr[1]),
BrDokKom = Convert.ToInt32(dr[2]),
Datum = Convert.ToDateTime(dr[3]),
Status = (PorudzbinaStatus)Convert.ToInt32(dr[4]),
MagacinID = Convert.ToInt32(dr[5]),
PPID = (dr[6] is DBNull) ? (int?)null : Convert.ToInt32(dr[6]),
InterniKomentar = (dr[7] is DBNull) ? null : dr[7].ToString(),
ReferentObrade = (dr[8] is DBNull) ? (int?)null : Convert.ToInt32(dr[8]),
NacinUplate = (PorudzbinaNacinUplate)Convert.ToInt32(dr[9]),
Tag = JsonConvert.DeserializeObject<Properties>(dr["TAG"].ToString())
});
}
}
I put breakpoint and it passes good paramter to query but doesn't enter while() loop (so i is not reading) and it returns no rows.
When i enter same query in my mysql and replace #MOB with parameter passed there, it does return me one row.
I guess problem is something with passing LIKE through c# but not sure why it does that.
You need to change how you are adding parameters slightly:
In your SQL, no quotes and no % symbols.
using (MySqlCommand cmd = new MySqlCommand(#"SELECT PORUDZBINAID, USERID, BRDOKKOM, DATUM,
STATUS, MAGACINID, PPID, INTERNIKOMENTAR, REFERENT_OBRADE, NACIN_PLACANJA, TAG FROM
PORUDZBINA WHERE TAG LIKE #MOB", con))
{
Then the parameter like this, without quotes.
cmd.Parameters.AddWithValue("#MOB", "%" + Mobilni + "%");
BTW: Ideally you should not use AddWithValue, but rather Add(). See this blog:
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
And this SO post:
MySqlCommand Command.Parameters.Add is obsolete
Instead, it should be like this:
cmd.Parameters.Add("#MOB", SqlDbType.Varchar).Value = "%" + Mobilni + "%";
//you must update to use the correct DBType for your data
Since #MOB is inside single quotes, it's interpreted as a string literal, which isn't what you meant. You can fix this by concatenating the placeholder to the % characters:
using (MySqlCommand cmd = new MySqlCommand(
#"SELECT PORUDZBINAID, USERID, BRDOKKOM, DATUM, STATUS, MAGACINID, PPID, INTERNIKOMENTAR, REFERENT_OBRADE, NACIN_PLACANJA, TAG
FROM PORUDZBINA
WHERE TAG LIKE CONCAT('%', #MOB, '%')", con))

ExecuteScalar returning wrong value

I have a little problem with selecting max ID from my database. This is my code:
string checkcat = "SELECT MAX(PRODUCT_ID) FROM CMS_PRODUKTY WHERE (CATEGORY_ID = CATEGORY_ID) AND (CLIENT_ID = #CLIENT_ID)";
SqlCommand cmd2 = new SqlCommand(checkcat, con);
cmd2.Parameters.Add("#CATEGORY_ID", System.Data.SqlDbType.Int).Value = kategoria;
cmd2.Parameters.Add("#CLIENT_ID", System.Data.SqlDbType.Int).Value = HiddenField1.Value;
con.Open();
int noweid = Convert.ToInt32(cmd2.ExecuteScalar());
con.Close();
The point is the new int "noweid" should be 1 or higher - depend on product_id inside table, but it's returning 0. I don't have any idea why... The other variables - kategoria and HiddenField1.Value are correct.
Any ideas what did I do wrong?
You have
WHERE (CATEGORY_ID = CATEGORY_ID)
but you want
WHERE (CATEGORY_ID = #CATEGORY_ID)
You should also parse the string to int:
cmd2.Parameters.Add("#CLIENT_ID", System.Data.SqlDbType.Int).Value = int.Parse(HiddenField1.Value);
maybe kategoria is also a string, then parse it also to int.

Data Type Mismatch error in Criteria expression in Select query C# query

My sample code is as follows, I am getting following error;
Data Type Mismatch error in criteria expression.
Details => ScannerAlarmLimits is my table from .mdb database.
string jointS = dsetChamberS1.Tables[0].Rows[tot][0].ToString();
int select1S = Convert.ToInt32(jointS);
string sqlQuery1S = "SELECT TMin,TMax,HMin,HMax from ScannerAlarmLimits WHERE ScannerID='" +select1S+ "'";
OleDbCommand cmd1S = new OleDbCommand(sqlQuery1S, conn);
OleDbDataAdapter adapter1S = new OleDbDataAdapter(cmd1S);
adapter1S.Fill(dsetTempS, "ScannerAlarmLimits");
I just added single quote in the condition of where clause, now its working.
var query = "SELECT * from checkinout where read <> '1'";
If your ScannerID column is integer, then you should not use single quotes with it. Single quotes are for characters. Like;
WHERE ScannerID = " + select1S;
But as a better way, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. Aka bobby-tables.
And use using statement to dispose your connections, commands and adapters.
string jointS = dsetChamberS1.Tables[0].Rows[tot][0].ToString();
int select1S = Convert.ToInt32(jointS);
using(var conn = new OleDbConnection(conString))
using(var cmd1S = conn.CreateCommand())
{
cmd1S.CommandText = "SELECT TMin,TMax,HMin,HMax from ScannerAlarmLimits WHERE ScannerID = #id";
cmd1S.Parameters.AddWithValue("#id", OleDbType.Integer).Value = select1S;
using(var adapter1S = new OleDbDataAdapter(cmd1S))
{
adapter1S.Fill(dsetTempS, "ScannerAlarmLimits");
}
}

Updating 2 rows in SQL database with one query string "UPDATE"

I need to figure out how to update the two rows in my database but cnt get my query string correct..
Here is the code that I am using. If you could provide me with a query string that would be great..
string birdnametextupdate = birdsnametext.Text;
string birdnamedetailsupdate = birdnamedetails.Text;
int row = int.Parse(Request.QueryString["PhotoID"]);
string query = "UPDATE Photos Set PhotoName = #PhotoNewName Set Deatils = #DetailsNew WHERE PhotoID = #PhotoID";
SqlCommand myCommand = new SqlCommand(query, myConnection);
//create parameterised object
myCommand.Parameters.AddWithValue("#PhotoNewName", birdnametextupdate);
myCommand.Parameters.AddWithValue("#DetailsNew", birdnamedetailsupdate);
myCommand.Parameters.AddWithValue("#PhotoID", row);
myCommand.ExecuteNonQuery();
try this
string query = "UPDATE Photos Set PhotoName = '#PhotoNewName' ,Details = '#DetailsNew' WHERE PhotoID = '#PhotoID'";
I saw error in your query, do not duplicate set. just use comma instead
int photoId = int.Parse(Request.QueryString["PhotoID"]);
string query = "UPDATE Photos SET PhotoName = #PhotoNewName, Details = #DetailsNew WHERE PhotoID = #PhotoID";
using(var cmd = new SqlCommand(query, myConnection))
{
cmd.Parameters.Add("#PhotoNewName").Value = birdsnametext.Text;
cmd.Parameters.Add("#DetailsNew").Value = birdnamedetails.Text;
cmd.Parameters.Add("#PhotoID").Value = photoId;
cmd.ExecuteNonQuery();
}
The Sql syntax is:
https://msdn.microsoft.com/en-us/library/ms177523.aspx
A simple example is:
UPDATE <tableName>
SET
<Column1> = <newColumn1Value>
,<Column2> = <newColumn2Value>
WHERE <condition>

SQL replace two records while cloning a row

I have coded this snippet to clone a selected row in a table:
protected void Button4_Click(object sender, EventArgs e)
{
DateTime ucode = DateTime.Now;
string slctedProj = DropDownList1.SelectedItem.ToString();
string new_code = "PR" + ucode.ToString("ssmmHHddMM");
string query = #"INSERT INTO Projects (proj_id, proj_prod_id, proj_cust_id, proj_man_id,
proj_name, proj_date, proj_num_of_vehicles, proj_coach_vehicle,
proj_contract_value, proj_length, proj_width, proj_height, proj_passenger_seats,
proj_passenger_total, proj_type, proj_notes, uname, proj_brand, proj_systemvoltage,
proj_gauge, proj_service_speed)
SELECT proj_id, proj_prod_id, proj_cust_id, proj_man_id,
proj_name, proj_date, proj_num_of_vehicles, proj_coach_vehicle,
proj_contract_value, proj_length, proj_width, proj_height, proj_passenger_seats,
proj_passenger_total, proj_type, proj_notes, uname, proj_brand, proj_systemvoltage,
proj_gauge, proj_service_speed
FROM Projects WHERE proj_name =" + "'" + slctedProj + "'";
System.Windows.Forms.MessageBox.Show(query);
string getconnstring = ConfigurationManager.ConnectionStrings["stad_conn"].ConnectionString;
SqlConnection conn = new SqlConnection(getconnstring);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
the code is working fine but I need to replace in the new row, "proj_id" with the string "new_code" and attach at the beginning of the "proj_name" something like "Cloned".
How can I do that?
First of all: Use parameters in your SQL command.
Heres the revised code, with parameters. Note that the Add method on the parameters is specifying both the data type as well as the length. It's better to specify these explicitly rather than let ADO.Net assume it knows what you want.
DateTime ucode = DateTime.Now;
string slctedProj = DropDownList1.SelectedItem.ToString();
string new_code = "PR" + ucode.ToString("ssmmHHddMM");
string new_projectName = "Some new name";
string query = #"INSERT INTO Projects (proj_id, proj_prod_id, proj_cust_id, proj_man_id,
proj_name, proj_date, proj_num_of_vehicles, proj_coach_vehicle,
proj_contract_value, proj_length, proj_width, proj_height, proj_passenger_seats,
proj_passenger_total, proj_type, proj_notes, uname, proj_brand, proj_systemvoltage,
proj_gauge, proj_service_speed)
SELECT #NewProjectID, proj_prod_id, proj_cust_id, proj_man_id,
#NewProjectName, proj_date, proj_num_of_vehicles, proj_coach_vehicle,
proj_contract_value, proj_length, proj_width, proj_height, proj_passenger_seats,
proj_passenger_total, proj_type, proj_notes, uname, proj_brand, proj_systemvoltage,
proj_gauge, proj_service_speed
FROM Projects WHERE proj_name = #SelectedProj";
System.Windows.Forms.MessageBox.Show(query);
string getconnstring = ConfigurationManager.ConnectionStrings["stad_conn"].ConnectionString;
SqlConnection conn = new SqlConnection(getconnstring);
conn.Open();
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add("#NewProjectID", SqlDbType.VarChar, 20).Value = new_code;
cmd.Parameters.Add("#NewProjectName", SqlDbType.VarChar, 20).Value = new_projectName;
cmd.Parameters.Add("#SelectedProj", SqlDbType.VarChar, 20).Value = slctedProj;
cmd.ExecuteNonQuery();
conn.Close();
This is not an answer. You could improve this design by keeping a reference to source / initial project using a FK (only for cloned projects) thus:
ALTER TABLE dbo.Projects
ADD source_proj_id INT NULL
REFERENCES dbo.Projects(proj_id);
GO
and you need to change also the insert statement thus:
string query = #"INSERT INTO Projects
(proj_id, source_proj_id, proj_prod_id, ...)
SELECT #NewProjectID, proj_id, proj_prod_id, ...
FROM Projects WHERE proj_name = #SelectedProj";

Categories