INSERT BYTE[] TO Sql Without parameter - c#

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....

Related

How to write comma to .csv files C#

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]}\")";

C# : Why is the value of empno between single quotes even though the empno is defined as an integer?

string sql = "select * from e where empno= ' " + datagridview.currentrow.cells(0).value.tostring() + " ' ";
Why is the value of empno between single quotes even though the empno is defined as an integer?
May i make a suggestion to make your code easier to read.
When working with string formatting, use interpolation rather than the '+' operator.
String interpolation provides a more readable and convenient syntax to create formatted string.
Example :
// Replace this line
string sql = "select * from e where empno= ' " + datagridview.currentrow.cells(0).value.tostring() + " ' ";
// By this one
string sql = $"select * from e where empno='{datagridview.currentrow.cells(0).value.tostring()}'";
Documentation : String Interpolation

Clause Select in Datatable

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);

how to insert newline after word in sql table in c#

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.

Write Image to SQL Server using Blob Literal String in C#

I have a c# function that needs to write to a SQL image column. I have the image in a byte array. The standard seems to be the use of SqlCommand while passing the byte array as a parameter of type System.Data.SqlDbType.Image.
Unfotunately, my function can only use text queries (don't ask why) so I have to find a way to use T-SQL commands only. What I have so far can write to the column but I don't know what format of string to make the image blob string.
sql = "DECLARE #ptrval binary(16)" +
"SELECT #ptrval = textptr(Photo) FROM EMPhoto WHERE Employee='" + employeeID + "'" +
"WRITETEXT EMPhoto.Photo #ptrval " + imageByteArrayAsString;
I've tried converting imageByteArray to a Hex string and Binary string but it doesn't seem to end up correct in SQL or in the application that reads it.
A T-SQL Binary constant is an unquoted hexidecimal string prefixed with 0x. ie 0xFFD8FFE0...
string imageByteArrayAsString = "0x" + BitConverter.ToString(image).Replace("-", string.Empty);

Categories

Resources