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);
Related
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]}\")";
I'm using SQL Server 2014 Enterprise and Visual Studio 2103.
I have hundreds of TSV files that contain foreign characters that I'm importing into SQL Server. I have a SSIS package that automates this (just a script task that I found online that uses C#). Tables are created with NVARCHAR(MAX) datatype for all columns, then each file is read line by line by the script, with the values inserted into the tables.
The source TSV files are exported as Unicode, but SQL Server doesn't seem to care - it imports the files as VARCHAR (i.e., Chinese characters come over as "?????"). If you manually import the file into SQL Server, the code page shows "65001 (UTF-8)" so I'm not sure why the datatypes default to VARCHAR.
Now, I suppose I can configure a DATA CONVERSION TRANSFORM for each of the files, but there are too many files and I'm thinking this can be done on the fly within the script task insert:
SCRIPT TASK:
Some variables for encoding:
Encoding ascii = Encoding.ASCII;
Encoding unicode = Encoding.Unicode;
Encoding utf8 = Encoding.UTF8;
Encoding utf32 = Encoding.UTF32;
The following part of the script task code is where I try to convert the encoding (the first part of the IF statement (not shown) creates the receiving table). It errors out where indicated:
else
{
//ADJUST FOR SINGLE QUOTES:
line = line.Replace("'", "''");
byte[] unicodeBYTES = unicode.GetBytes(line);
byte[] unicodeCONVERT = Encoding.Convert(unicode, utf8, unicodeBYTES); <--- ERRORS OUT
char[] unicodeCHARS = new char[unicode.GetCharCount(unicodeCONVERT, 0, unicodeCONVERT.Length)];
unicode.GetChars(unicodeCONVERT, 0, unicodeCONVERT.Length, unicodeCHARS, 0);
string NEWline = new string(unicodeCHARS);
string query = "Insert into " + SchemaName + ".[" + TableName + "] (" + ColumnList + ") ";
query += "VALUES('" + NEWline + "')";
// MessageBox.Show(query.ToString());
SqlCommand myCommand1 = new SqlCommand(query, myADONETConnection);
myCommand1.ExecuteNonQuery();
}
However, If I change the line:
byte[] unicodeCONVERT = Encoding.Convert(unicode, utf8, unicodeBYTES);
to the following:
byte[] unicodeCONVERT = Encoding.Convert(unicode, unicode, unicodeBYTES);
It loads the data, but is still in ASCII format (with "?????" characters).
Any help would be appreciated.
Thank you.
Is there a way/function/reg-ex in SQL Server or Visual Studio by which we can escape any character/special character within a string?
I have a functionality/page where there are server text field and user can enter any kind of string there (including special characters). And as a result I am showing a JSON string as a 'Key', 'Value' pare of those text fields entries.
For ex: I have these fields on a page:
Name , LastName , Address
And the entered values for above fields are:
Name : *-+-#. Wwweee4426554456666yyyy5uuuuttrrrreree6655zfgh\\][;'/.uuuuuuuu66uuyt,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\
LastName : Piterson
Address : Park Road, LA
And I am showing the output like a JSON string below-
[{"Key":"Name","Value":"*-+-#.Wwweee4426554456666yyyy5uuuuttrrrreree6655zfgh\\][;'/.uuuuuuuu66uuyt,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\\\"?><\\\\][;'/.,+_)(*&^%$##!~|}{:\"},{"Key":"LastName","Value":"Piterson"},{"Key":"Address","Value":"Park Road, LA"}]
But while parsing this string I am getting a parsing error below -
"After parsing a value an unexpected character was encountered: K. Path '[4].Value', line 1, position 1246."
I am using below SQL Server function to parse the string -
ALTER function [dbo].[fnEscapeString](#text nVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
as
BEGIN
--if(CHARINDEX() )
if (CHARINDEX('\',#text) > 0)
set #text = Replace(#text,'\','\\')
if (CHARINDEX('"',#text) > 0)
set #text = Replace(#text,'"','\"')
return #text
END
This function is working in many other cases (with many other strings). But not working with above string. I think this function is not enough able to parse all kind of strings.
So is there any way where we can parse a string in a valid JSON row format. May be any reg-ex or sql function can do that. Please suggest.
You can directly convert your table data to json in 2016 for example,
SELECT name, surname
FROM emp
FOR JSON AUTO
but in case of lower versions you have to convert your sql table data to xml and then to Json.
Please refer this link to parse SQL Data to Json.
http://www.codeproject.com/Articles/815371/Data-Parsing-SQL-to-JSON
You can try this as mentioned here
var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
eval('(' + text + ')');
Try converting the input string to JSON by using:
a) System.Web.HttpUtility.JavaScriptStringEncode
string jsonEncoded = HttpUtility.JavaScriptStringEncode(s)
or
b) NuGet Package Newtonsoft.Json
string jsonEncoded = JsonConvert.ToString(s)
Reference: How to escape JSON string?
I have the following scenario-
User may enter text in any language in the text box and need to store it in my database along with language name. Following is the code for this on button Update
Dim conStr As String = "Dsn=search;database=search;description=search;option=0;port=0;server=localhost;uid=root;CharacterSet=UTF8;"
Dim s As String = txtLanguage.Text '<----"音読み現代仮名遣い人名用漢字"
mySQL = "INSERT INTO multi_language(language, characters)" & _
" VALUES ('Japanese', '" & s & "')"
con.ConnectionString = conStr
con.Open()
cmd = New OdbcCommand(mySQL, con)
cmd.ExecuteNonQuery()
con.Close()
screen short for running the query
after clicking button the text in the Textbox becomes '??????'
and the data inserted in the data base is like the following
Language | characters
--------------------------
Japanese | ?????
My table structure is
CREATE TABLE multi_language
(
id INTEGER NOT NULL AUTO_INCREMENT,
language VARCHAR(30),
characters TEXT,
PRIMARY KEY(id)
) ENGINE=INNODB CHARACTER SET = utf8;
when i execute the query directly in the query browser then it will executed properly,
whats wrong with my coding? what i need to add to get proper result?
This is the screenshot for the comparison of insert from the
I am also suffering from a similar situation, i solved it in a different way as follows:
while inserting Use your Query as :
Dim s As String = txtLanguage.Text '<----"音読み現代仮名遣い人名用漢字"
mySQL = "INSERT INTO multi_language(language, characters)" & _
" VALUES ('Japanese', '" & encodeUTF(s) & "')"
Encode the string before inserting
Public Function encodeUTF(ByVal inputString As String) As String '<-- function for encoding the input string
Dim byt() As Byte = uni.GetBytes(inputString)
encodeUTF = ""
For Each b As Byte In byt
encodeUTF &= b & ","
Next
Trim(Replace(encodeUTF, ",", ""))
End Function
decode the string before retriving
Public Function decodeUTF(ByVal inputString As String) As String '<-- function for decoding the input string
Dim strs() As String
strs = inputString.Split(",").ToArray
Dim temp(strs.Length) As Byte
Dim i As Integer
For i = 0 To strs.Length - 2
temp(i) = Byte.Parse(strs(i))
Next
decodeUTF = uni.GetString(temp)
decodeUTF = decodeUTF.Substring(0, Len(decodeUTF) - 1)
End Function
While Retrieving this text to a text box you can use your query as :
mySQL = "Select language, characters from multi_language"
Reader = objdb.GetDataReader(mySQL)'<--- is a class function which returns the datareader
If Reader.HasRows = True Then
Reader.Read()
txtlang.Text = objOdbcDataReader.Item("language")'<--- display the selected language
txtchar.Text = objOdbcDataReader.Item("characters ")'<--- display the selected characters
End If
You can try this proposed solution,
If your application want to save data in to database in multiple language, make sure your database stores data in UTF-8 and also the connection to your database is in UTF-8 (commonly people forget this).
Make sure to Execute this query when establishing a connection:
mysql_query("SET NAMES utf8");
In Your application end, where user input data, set the accept-charset attribute on your forms.
<form accept-charset="utf-8">
Set appropriate meta tags for your site:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
or Serve your sites with an appropriate HTTP header:
header('Content-Type: text/html; charset=utf-8');
So overall the problem is, everything is not in UTF-8, If you keep everything in UTF-8, usually don't need to worry about anything.
Refer Strategy for supporting unicode & multi language in PHP5
Storing and displaying unicode string (हिन्दी) using PHP and MySQL
perhaps you should use parametrized query (which anyway is always a better choice than string concatenation, which is susceptible to sql injection)
modify your query to use parameters (I am not sure if for mysql the #param is correct syntax):
"INSERT INTO multi_language(language, characters) VALUES ('Japanese', #val)"
then add parameter to your query:
cmd = New OdbcCommand(mySQL, con)
cmd.Parameters.AddWithValue("#val", txtLanguage.Text)
cmd.ExecuteNonQuery()
con.Close()
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....