I have the following query -
string query = "Insert into table(userId,companyID) values(" + userId + "," + SplitedLine[1] + ")";
writer.WriteLine(query);
When I am printing running this code then it is not printing the entire query in one column, rather it is breaking the query wherever there is a comma.
I tried this
How to write a value which contain comma to a CSV file in c#?
string query = "Insert into table(userId" +"\",\""+"companyID) values (" + userId + "\",\"" + SplitedLine[1] + ")";
writer.WriteLine(query);
But this is printing my insert commands in wrong format.
Please help.
Having tested this out, your simplest approach is to ensure that your query string is double quoted.
var query = $"\"Insert into table(userId,companyID values ({userId}, {SplitedLine[1]})\"";
I think the title of your question is ambiguous. You wanted to soround the values by quotation marks ("). But you made a mistake by escaping the " in the table part, it seams escaped " and not escaped was misked up.
Try to go with
string query = $"Insert into table(\"{userId}\",\"{companyID}\") values(\"{ userId}\",\"{SplitedLine[1]}\")";
Related
I'm trying to do some Selects in a Datatable, but I am having some problems because I have values in some cells like this: 'COX-12-3SCS4CSCH
This value has ' and -
I tried to do this select but doesn't work:
string expression = "Nivel='" + lvfin + "' AND [Nivel " + lvfin + "]='" + codActual + "'";
DataRow[] results = DataTable.Select(expression);
lvfin contains for example 0 and codActual contains 'COX-12-3SCS4CSCH
And I get this error:
Missing operand after operator 'COX'
What is the problem here?
If your field name is Nivel 0 then you need to add that zero to the constant string "Nivel" and enclose the whole field name into square brackets to form the correct field name used in the first condition, then, if the value that you search contains a single quote, then you need to double it. All this is necessary to avoid confusing the parser when you use a single quote as delimiter for string values or your field names contains spaces.
So you should write (line by line for clarity but could be written in a single line):
string fieldName = "Nivel " + lvfin.ToString();
string searchValue = codActual.Replace("'", "''");
string expression = $"[{fieldName}]='{searchValue}'";
DataRow[] results = DataTable.Select(expression);
I'm completely lost with what is happening here.
string send = "!points add " + entries[winner] + " " + prize.ToString();
What I want to send is "!points add winnername prizeamount" but what I get is "!points add winnername\nprizeamount". I put \n because it writes a new line but trying to replace "\n", "\r" and "\t" with " " does nothing.
enter image description here
all I need is the message to be exactly"!points space add space winnername space prizeamount space"
If it's important the entries in my code is a List of strings
The entries strings already contain the new line character(s).
I suggest you replace with Environment.NewLine:
Replace Line Breaks in a String C#
The string object, 'entries[winner]' is having line-feeds (LF) or carriage-returns (CR). You try this to remove all LFs and CRs,
string send = "!points add "
+ entries[winner].Replace("\r", string.Empty).Replace("\n", string.Empty)
+ " " + prize.ToString();
Alternatively, you can use Trim() to remove leading\ trailing LFs\ CRs.
string send = "!points add "
+ entries[winner].Trim()
+ " " + prize.ToString();
No repro. The following code doesn't assert.
var entries=new List<string>{"Aaa", "Bbb", "Ccc"};
int prize=90;
int winner=1;
var send=String.Format("!points add {0} {1}",entries[winner],prize);
var send2="!points add " + entries[winner] + " " + prize.ToString();
Trace.Assert("!points add Aaa 90"==send);
Trace.Assert(send2==send);
If the result contains newlines, it's because the entries values contain newlines.
The best solution would be to clean the input data before storing it in the list, eg with String.TrimEnd or String.Trim, When loading data from a file for example, you can't be sure it doesn't contain trailing spaces.
To read clean data from a file you could use :
var entries=File.ReadLines()
.Select(line=>line.Trim())
.ToList();
If you add the entries one by one from user input :
entries.Add(newEntry.Trim());
If you can't change how the data is read (why?) you can trim when whenever you use an entry value:
var send=String.Format("!points add {0} {1}",entries[winner].Trim(),prize);
Loading clean data is a lot easier
I am trying to insert New Line after word car but it is not working with folowing solution
Char(13) - not working
Environment.NewLine - when i use this it works but appends '(' this char in sql rows like 'Car ( Rate:2CR'
\n\r - not working
Code:
cmd.Parameters.AddWithValue("#ColumnCar", Car + "char(13)" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + "\n\r" + "Rate:2CR";
//cmd.Parameters.AddWithValue("#ColumnCar", Car + Environment.NewLine + "Rate:2CR";
cmd.ExecuteNonQuery();
Need output in sql table ColumnCar row value as follows:
Car
Rate:2cr
Note : here after Car there will be a newline and then Rate:2Cr will be added
With the LoC Car + "char(13)" + "Rate:2CR"; you will get a literal string "char(13)" between your 2 values, not a new line. If you want only a new line you can append "\n" or you can append the character equivalent (char)10 of new line.
Now what character or string actually represents a new line might depend on your environment including the collation you are using. In simple ascii/ansi this will work. It might not be the same for another collation. As #mhasan pointed out it could also be different depending on the O/S.
Using characters
const char carriageReturn = (char) 13; // see https://en.wikipedia.org/wiki/Carriage_return
const char newLine = (char) 10;
var car = "some car";
var toInsert = car + newLine + "Rate:2CR";
cmd.Parameters.AddWithValue("#ColumnCar", toInsert);
This would also work and produce the same result:
var toInsert = car + "\n" + "Rate:2CR";
Use combination of newline and carriage return characters i.e. char(13) + char(10) for inserting new line in windows OS system.
For MAC its \r char(13) , for Linux its \n i.e. char(10) but for windows its combination of both.
Try this code hope its working...
Make a string variable and store all value in variable..
ex: string abc=textbox1.text+" "+"Rate:2cr";
#ColumnCar=abc.tostring();
now put your code
cmd.Parameters.AddWithValue("#ColumnCar",datatype);
cmd.executenonquery();
The following code works fine with unicode fields in a MS SQL-Server 2016 DB :
string carString = $"Volvo{Environment.NewLine}Rate: 2CR";
SqlParameter parameter = new SqlParameter("#ColumnCar", carString);
command.Parameters.Add(parameter);
The '(' when you use Environment.NewLine must be another error somewhere else. What is Car in your code? A class instance? What does its ToString() expand to?
Don't use string1 + " " + string2 concatenation.
Use string.Format(), $"" - inline syntax (like above) or StringBuilder to build your strings.
I want to make a raw SQL query that adds an encrypted value (byte[]) to an SQL column (varbinary) without using parameter like this:
byte[] value = GetEncryptedValue();
string query = "INSERT INTO Table1 VALUES('" + value.ToString() + "')";
the column datatype that I want insert into is varbinary. I need some function that uses value.ToString() instead. How to write this ?
i just need function like master.dbo.fn_varbintohexstr in sql!!!
A binary literal takes the form 0x6ABCDEF, i.e. 0x followed by bytes in hexadecimal form.
You can use this to turn the byte array into a literal value:
string literal = "0x" + String.Join("", value.Select(n => n.ToString("X2")));
There are not apostrophes around the binary literal:
string query = "INSERT INTO Table1 VALUES(" + literal + ")";
Another way to do it, is by using BitConverter
byte[] value = GetEncryptedValue();
string query =
"INSERT INTO Table1 (c1) VALUES(0x" + BitConverter.ToString(value).Replace("-", "") + ")";
BitConverter.ToString returns something like 01-02-03....
I want to form a string as <repeat><daily dayFrequency="10" /></repeat>
Wherein the value in "" comes from a textboxe.g in above string 10. I formed the string in C# as
#"<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>" but i get the output as
<repeat><daily dayFrequency="+ txt_daily.Text+ " /></repeat>. How to form a string which includes the input from a textbox and also double quotes to be included in that string.
To insert the value of one string inside another you could consider string.Format:
string.Format("foo {0} bar", txt_daily.Text)
This is more readable than string concatenation.
However I would strongly advise against building the XML string yourself. With your code if the user enters text containing a < symbol it will result in invalid XML.
Create the XML using an XML library.
Related
How can I build XML in C#?
Escape it with \ Back slash. putting # in front wont do it for you
string str = "<repeat><daily dayFrequency=\"\"+ txt_daily.Text + \"\" /></repeat>";
Console.Write(str);
Output would be:
<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>
You could do it like this:
var str = String.Format(#"<repeat><daily dayFrequency="{0}" /></repeat>",
txt_daily.Text);
But it would be best to have an object that mapped to this format, and serialize it to xml
string test = #"<repeat><daily dayFrequency=" + "\"" + txt_daily.Text + "\"" + "/></repeat>";