Parametrized hexadecimal literal in DB2 C# IBM driver - c#

There is DB2 database.
There is C#.NET application, which uses IBM.Data.DB2 driver to connect to the database (IBMDB2).
There is a parametrized query (DB2Command object, initialized with):
"SELECT $coid_ref FROM db.$ext WHERE $coid = #coid"
It's needed to substitute #coid with hexadecimal literal. For example, it should be executed like this:
"SELECT $coid_ref FROM db.$ext WHERE $coid = x'AA23909F'"
But, when I try to add parameter via command.Parameters.Add("#coid", "AA23909F") driver tries to add it as string, which leads to error. How can I solve this?

You are passing in a regular string.
You need to use a hexadecimal literal value.
From what I could find...
command.Parameters.Add("#coid", "\xAA\x23\x90\x9F")
What DB2 platform are you working with? If an EBCDIC platform (IBM i or z/OS) you might have a problem with your string being translated...
But this seems to be a really strange need. Is the column really defined as a 4 byte binary string? (is so it should look like CHAR(4) FOR BIT DATA assuming you're not using unicode.)

Related

How to pass list of guid as a parameter to a sql command

I need to filter a sql request by passing a list of id to , this is the command:
var command = "select Software.Name as SoftwareName,SoftwareType.Name as SoftwareType from AssetManagement.Asset as Software inner join AssetManagement.AssetType as SoftwareType on (SoftwareType.Id = Software.TypeId) where Software.Id in (#P)";
cmd.Parameters.AddWithValue("#P", authorizedSoftwaresId);
authorizedSoftwaresId is a list of string , containing data like :
"7D23968B-9005-47A9-9C37-0573629EECF9,F1982165-3F6D-4F35-A6AB-05FA116BA279"
with that it returns to me just one row, I tried adding quotes foreach value but i got "converstion from string caractere to uniqueidentifier failed " exception
This is a pretty common problem and the answer might depend on your database engine and whether you're using ADO.Net, Dapper, etc.
I'll give you some hints from my own experience with this problem on both MS Sql Server and PostgreSQL.
A lot of people think AddWithValue is a devil. You might consider Add instead.
The IN (#P) in your SQL statement might be the source of your problem. Try the Any option instead. See Difference between IN and ANY operators in SQL ; I've had success with this change in similar situations.
If all of your inputs are GUIDs, you might consider changing the type to a collection of GUIDs, although I don't think this is the fix, you have to try everything when you're stuck.
If you have to, you can parse the string version of your collection and add the ticks (') around each value. This choice has consequences, like it may prevent you from using a parameter (#P), and instead construct the final SQL statement you desire (i.e., manually construct the entire WHERE clause through string manipulations and lose the parameter.)
Good luck.

Avoiding reference to schema in queries in postgresql

Being new to C# and postgresql, but not to development and DBs, I'm trying to make the connection from C# .NET to postgresql. I keep running into the same syntax error.
In postgresql I have created a table "Test" with one column "Text".
To insert data into the table, in pgAdmin 4, I use:
insert into public."Test" ("Text") values('It Works!')
This works.
Now I try this in C# where I have a working connection to the database:
1 NpgsqlCommand cmd = new NpgsqlCommand("insert into Test ("Text") values('It Works!')", postconn);
2 cmd.ExecuteNonQuery();
This gives me a compilation error. Apparently from all the double quotes.
If I change the command text to:
"insert into Test ('Text') values('It Works!')"
with single quotes around Text the compiler is happy, but Npgsql gives me a syntax error.
Questions:
In pqsql:
I can see from google that it's possible to get around use the double quotes and the schema reference in psql.
But what does it take?
In C#:
Is there a way to construct the string, so that the compiler will accept it?
pgAdmin 4 is version 1.0
PostgreSQL is version 9.6
C# I believe is the most recent version.
In addition to the comment about escaping your quotes, you really should use parameters instead of literals. It may seem like more work initially, but it's:
Safer (SQL-injection proof)
Easier on the database -- supports compile once, execute many
Avoids having crazy SQL statements within C# that have concacts or string.format all over the place
Avoids the need to single quote literal values and omit quotes for numbers, booleans
Strong datatyping means no formatting (dates, for example)
Here is your code with parameters:
NpgsqlCommand cmd = new NpgsqlCommand("insert into Test (\"Text\") " +
" values(:TEST)", postconn);
cmd.Parameters.AddWithValue("TEST", "It Works");
cmd.ExecuteNonQuery();
Seems like I made your life harder, but your example was a trivial one. As you move to complex SQL statements with multiple parameters and different datatypes, you will see the true value.
On a final rant, while there is nothing technically wrong with making case-sensitive field names, it sure does cause nothing but headaches. Yours is a perfect example. Without the double quotes around the field "Test", you wouldn't have had an issue to begin with.

SQLServer nchar and .Net unicode with special F801 charcter

I have an existing database with existing data that I can't change it's structure or values.
In that database there is a nvarchar column that contains values in the twilight unicode zone starting with F800, upward.
When I select those values in SQL or use SQL function, unicode - I get the proper values.
When I select the same values in .Net - I get an error value - all the values in that twilight zone become 65533.
I need those values - how can I presuade .Net to give me those values - something like chaninging the connection encoding to a custom one - or ucs-2 etc...
Here is a sample code that demonstraits the problem:
c.CommandText = "select NCHAR(55297)";
using (var r = c.ExecuteReader())
{
r.Read();
var result = r[0]; //expected 55297 but got 65533
}
55297 is D801 which isn't defined? you probably want f801 which is 63489? But it appears as if that one isn't defined either. Which characters do you want?
If I try doing a "select NCHAR(55297)" in SQL Server Management studio, I get back the diamond question mark, but if I do "select NCHAR(63489)" I get back a dot of some sort: 
If what you want is the character values, you can ask for them directly:
select Unicode(NCHAR(63489))
This returns 63489 (as an integer)
If you want them as a byte array, you can ask for that:
select CONVERT(varbinary(MAX), FieldThatIsAnNvarchar) from ThatTable
After much investigations I failed to find any way around this. I couldn't find any two way conversion that would work here.
It seems that some unicode values are intended for some strange unicode scenario that isn't supported by .Net, but is partially supported in a way that breaks what we need here.

SQLite issues, escaping certain characters

I'm working on my first database application. It is a WinForms application written in C# using a SQLite database.
I've come across some problems, when a apostrophe is used, my SQLite query fails. Here is the structure of my queries.
string SQL = "UPDATE SUBCONTRACTOR SET JobSite = NULL WHERE JobSite = '" + jobSite + "'";
For instance, if an apostrophe is used in the jobSite var, it offsets the other apostrophes in the command, and fails.
So my questions are:
1. How do I escape characters like the apostrophe and semicolon in the above query example?
2. What characters do I need to escape? I know I should escape the apostrophe, what else is dangerous?
Thanks for your help!
Rather use Parameters
There is a previous stack-overflow question about it
Adding parameters in SQLite with C#
if you need more functionality you can also use Entity Framework
http://sqlite.phxsoftware.com/
Sorry not to familiar with the Syntax but the concept should same.
Something like :
SQLiteCommand Command = "UPDATE SUBCONTRACTOR SET JobSite = NULL WHERE JobSite = #JobSite";
Command.Parameters.Add(new SQLiteParameter("#JobSite", JobSiteVariable));
command.ExecuteNonQuery();
to escape an apostrophe add another apostrophe...
so a string like it's should be inserted as it''s
You may also need to escape quotation marks. The way to do this is to use a backslash as an escape charater...
like so... 'and he said\"escape all those quotes\"'
You should also beware of SQL injections... depending on the type of programming language you are using there exist different functions that can help clean out any malicious code.
C# tutorial on SQL Injections for example
You should never concatenate strings to build SQL queries for SQLite - or for any other SQL DB if possible. It makes your code fragile and opens up potential entry points for injection attacks.
The proper way to do it is to use hosted parameters. This approach removes the need for cumbersome string filtering. I am not sure how to do that in C# for SQLite but any decent language binding for SQLite should allow you to use hosted parameters.

read/write unicode data in MySql

I am using MySql DB and want to be able to read & write unicode data values. For example, French/Greek/Hebrew values.
My client program is C# (.NET framework 3.5).
How do i configure my DB to allow unicode? and how do I use C# to read/write values as unicode from MySql?
Upddate: 7 Sep. 09
OK, So my Schema, Table & columns are set to 'utf8' + collation 'utf8_general_ci'. I run the 'set names utf8' when the connection is opened. so far so good... but, still values are saved as '??????? '
any ideas?
The Solution!
OK, so for C# client to read & write unicode values, you must include in the connection string: charset=utf8
for example: server=my_sql_server;user id=my_user;password=my_password;database=some_db123;charset=utf8;
of course you should also define the relevant table as utf8 + collation utf8_bin.
The Solution!
OK, so for C# client to read & write unicode values, you must include in the connection string: charset=utf8
for example: server=my_sql_server;user id=my_user;password=my_password;database=some_db123;charset=utf8;
of course you should also define the relevant table as utf8 + collation utf8_bin.
You have to set the collation for your MySQL schema, tables or even columns.
Most of the time, the utf8_general_ci collation is used because it is case insensitive and accent insensitive comparisons.
On the other hand, utf8_unicode_ci is case sensitive and uses more advanced sorting technics (like sorting eszet ('ß') near 'ss'). This collation is a tiny bit slower than the other two.
Finally, utf8_bin compares string using their binary value. Thus, it also is case sensitive.
If you're using MySQL's Connector/NET (which I recommend), everything should go smoothly.
try to use this query before any other fetch or send:
SET NAMES UTF8
You need to set the db charset to UTF-8 (if you are using utf-8), collation for relevant tables/fields to utf, execute SET NAMES 'UTF-8' before doing queries, and of course make sure you set the proper encoding in the html that is showing the output.

Categories

Resources