How to use "LIKE" in parameterized Cosmos query - azure-cosmosdb

I'm using The Azure.Cosmos API, version 3.17.1. If I run a query against my Cosmos collection as so, I get the results I expect:
string Sql = "SELECT c.LastName FROM c where c.LastName like 'Smi%'";
QueryDefinition oQry = new QueryDefinition(Sql);
FeedIterator<myObj> oFI = this.container.GetItemQueryIterator<myObj>(oQry); // returns Smith, Smithers, etc.
If I try to parameterize this, I get nothing back:
string Sql = "SELECT c.LastName FROM c where c.LastName like '#KeyWord%'";
QueryDefinition oQry = new QueryDefinition(Sql);
oQry.WithParameter(#KeyWord, "Smi");
FeedIterator<myObj> oFI = this.container.GetItemQueryIterator<myObj>(oQry);
Is this a syntax issue or something not supported?
Tks

Don't use % in your parameter names and don't need to quote it.
Please try this code:
string Sql = "SELECT c.LastName FROM c where c.LastName like #KeyWord";
QueryDefinition oQry = new QueryDefinition(Sql);
oQry.WithParameter("#KeyWord", "Smi%");
FeedIterator<myObj> oFI = container.GetItemQueryIterator<myObj>(oQry);

Related

.NET Core Informix multiple parameters in IfxCommand

This is the environment I work in:
.NET Core 3.1 (console application for testing purposes)
CSDK 4.50.FC5
Informix.Net.Core.dll from the CSDK 4.50.FC5 package
Informix Server 12.10
The problem I have is that some of the queries from my .NET Core app are executed successfully and results are retrieved from the Informix database, but sometimes I get weird errors that have to do something with parameters. Of course, I am trying to use IfxParameters in order to be safe from SQL Injection attacks.
This passes succesfully (table names and columns are made up). Here I am using positional parameters:
IfxCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * FROM employees WHERE name LIKE '%John%' SKIP ? LIMIT ?";
IfxParameter paramSkip = new IfxParameter("skip", IfxType.Integer);
paramSkip.Value = 30;
command.Parameters.Add(paramSkip);
IfxParameter paramLimit = new IfxParameter("limit", IfxType.Integer);
paramLimit.Value = 10;
command.Parameters.Add(paramLimit);
connection.Open();
using (IfxDataReader reader = command.ExecuteReader())
{
... // reading data from the IfxDataReader
}
Let's see now this example which produces an error:
IfxCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * FROM employees WHERE name LIKE ? SKIP 10 LIMIT ?";
IfxParameter paramSearch = new IfxParameter("searchQuery", IfxType.VarChar);
paramSearch.Value = "%John%";
command.Parameters.Add(paramSearch);
IfxParameter paramLimit = new IfxParameter("limit", IfxType.Integer);
paramLimit.Value = 10;
command.Parameters.Add(paramLimit);
con.Open();
using (IfxDataReader reader = command.ExecuteReader())
{
...
}
Error:
IfxException: ERROR [22018] [Informix][Informix ODBC Driver][Informix]A character to numeric conversion process failed
The only difference here is that I have parameters that are not of the same type. In the first example both parameters were IfxType.Integer, and now I have IfxType.Integer and IfxType.VarChar
Using named parameters doesn't help. For the following IfxCommand:
command.CommandText = "SELECT * FROM employees WHERE name LIKE '%John%' SKIP 10 LIMIT #limit";
I get the following error:
Error: IfxException: ERROR [42000] [Informix][Informix ODBC Driver][Informix]A syntax error has occurred.
I hope someone will be able to point me in the right direction in order to solve this issue. I am open to any suggestion that will solve this. If any further info is needed, please hit me up!
This is because of the precedence of positional parameters. "where" parameters have lower precedence than "skip" and "limit". Therefore, create the "where IfxParameter" parameters (paramSearch) at the end.
Try:
IfxCommand command = connection.CreateCommand();
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * FROM employees WHERE name LIKE ? SKIP 10 LIMIT ?";
IfxParameter paramLimit = new IfxParameter("limit", IfxType.Integer);
paramLimit.Value = 10;
command.Parameters.Add(paramLimit);
IfxParameter paramSearch = new IfxParameter("searchQuery", IfxType.VarChar);
paramSearch.Value = "%John%";
command.Parameters.Add(paramSearch);
...

Firebird insert...returning asp.net

I'm using Firebird 2.5 and asp.net (4.5).
I'm trying to find out how to use insert ... returning, or some equivalent.
Using fbDataReader, it executes the insert OK, but I can't find anyway of accessing a returned value. Using fbDataReader.GetName(0) seems to work ok, returning the variable name in the "returning" clause. This even applies to a max() in a subselect:
..... returning (select max(userid) as newid from users)
returns the text "newid".
I can't find where, or whether, the value is available.
Using a fbDataAdaptor to fill a DataTable, the insert works OK, but data table seems empty.
Does anyone know whether this is possible, and if so, how it's done?
Thanks
EDIT
Code supplied :
strConn = ....
dbConn = New FirebirdSql.Data.FirebirdClient.FbConnection(strConn)
dbConn.Open()
MySQL = "insert into users (Firstname, Lastname) VALUES (#fname,#lname) returning userid"
FbC = New FirebirdSql.Data.FirebirdClient.FbCommand(MySQL, dbConn)
FbC.Parameters.Add("fname", FirebirdSql.Data.FirebirdClient.FbDbType.Text).Value = "Pete"
FbC.Parameters.Add("lname", FirebirdSql.Data.FirebirdClient.FbDbType.Text).Value = "Davis"
FbDataReader = FbC.ExecuteReader()
FbDataReader.Read()
TextBox1.Text = FbDataReader.GetName(0)
'TextBox1.Text = str(FbDataReader.GetInt64())
'TextBox1.Text = FbDataReader.GetString(0)
TextBox1.Text = FbDataReader.GetValue(0)
According to this thread INSERT ... RETURNING ... behaves like output parameters for the Firebird .NET provider. So you will need to add an output parameter.
So something like the code below should work:
FbParameter outParam = new FbParam("userid", FbDbType.Integer)
{
Direction = ParameterDirection.Output
};
FbC.Parameters.Add(outParam);
FbC.ExecuteNonQuery();
int? userId = outParam.Value as int?;

Is it possible to save '0' character in sqlite as a text

I have an UTF string with \0 character and text field in a sqlite table.
When I tried to insert the string into table text field and then read it from the database I noticed that string value was truncated after \0 character.
Question: Is it possible to so save/restore such strings in sqlite without losing data after \0?
The code snippet:
public static void IssueWith0Character()
{
const string sql = "DROP TABLE IF EXISTS SomeTable;" +
"CREATE TABLE SomeTable (SomeField TEXT not null);"
+ "INSERT INTO SomeTable (SomeField) Values ( :value )";
var csb = new SQLiteConnectionStringBuilder
{DataSource = "stringWithNull.db", Version = 3};
// string with '0' character
const string stringWithNull = "beforeNull\0afterNull";
using (var c = new SQLiteConnection(csb.ConnectionString))
{
c.Open();
using (var cmd = c.CreateCommand())
{
var p = new SQLiteParameter(":value", DbType.String) {Value = stringWithNull};
cmd.CommandText = sql;
cmd.Parameters.Add(p);
cmd.ExecuteNonQuery();
}
using (var cmd = c.CreateCommand())
{
cmd.CommandText = "SELECT SomeField FROM SomeTable;";
var restoredValue = (string) cmd.ExecuteScalar();
Debug.Assert(stringWithNull == restoredValue);
}
}
}
UPDATE #1 It looks like problem is on reading stage. At least "afterNull" part of a string exists in the database file.
UPDATE #2 That was considered as System.Data.SQLite bug (<1.04.84). http://system.data.sqlite.org/index.html/tktview/3567020edf12d438cb7cf757b774ff3a04dc381e
In SQLite, \0 characters are considered invalid.
While it is possible to put such strings into the database (using the pointer+length form of various functions), many functions that operate on strings stop when encountering the \0. Therefore, the documentation says:
The result of expressions involving strings with embedded NULs is undefined.
If your really need to store data with null bytes, you should store it as a blob (DbType.Binary).

Flex SQLite Display SUM() result

I try to display the Total sum() from a sqlStmt but all i got is [object, object], any idea how?
Thanks
private function displayAmountHeading():void {
sqlStmt = new SQLStatement();
sqlStmt.sqlConnection = sqlConn;
sqlStmt.text = "SELECT SUM(Amount) FROM MainTable";
sqlStmt.execute();
var result:Array = sqlStmt.getResult().data;
if (result != null) trace(result);
}
//return [object, object]
You're attempting to trace an array. If you want to see the first value in that array, try
SELECT SUM(Amount) as sum FROM MainTable
trace(result[0].sum);
The object,object is the string representation of the object, without a toString() method. Use trace(ObjectUtil.toString(result)); If your new to the flex sqlStatement you should also read this and this
for more information about the return type of the sqlStatement and how to access properties of the result object, when using aggregate functions such as SUM, where u should use aliases, such as SUM(Amount) as sumAmount to later access the property, like resultObject["sumAmount"] or resultObject.sumAmount

DataGrid view in asp.net is not displaying data

I want to dispaly column in datagrid view using custom query statement
but i want to send value to parametrized data in query
how can i do this ?
my code is below
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'cus0010' and a.account_number = 'acc0010'
this above code working properly in sql server 2005
but the code below which is modified as per asp.net page for grid view is not showing
any result
select
c.customer_id,
c.customer_first_name,
c.customer_last_name,
c.customer_address,
c.account_number,
c.account_type,
a.account_balance,
t.transfer_amount_balance,
t.samebank_transfer_id,
t.account_number_same_bank,
t.transferdatetime
FROM customer_details c join account_details a on c.account_number = a.account_number
join transactions_details t on a.account_number = t.account_number where
c.customer_id = 'Label1.Text' and a.account_number = 'Label2.Text'
the above is placed in my custom sql query section it
is triggered by button click in my asp page or any other
idea to display it will be welcomed
Use:
string.Format("c.customer_id = '{0}' and a.account_number = '{1}'", Label1.Text, Label2.Text);
Consider this query:
string query = "insert into TestTable (Column1, Column2) values (#p1, #p2)";
p1 & p2 are parameters, in order to set the value for the parameters you need to use:
queryParameters[0] = new SqlCeParameter("p1", SqlDbType.NVarChar);
queryParameters[0].Value = Label1.Text;
queryParameters[1] = new SqlCeParameter("p2", SqlDbType.NVarChar);
queryParameters[1].Value = Label2.Text;
SqlCeCommand command = new SqlCeCommand(query);
command.Parameters.AddRange(queryParameters);
When the wizard is generating the query you need to use place holders/parameters for customer_ID and account_number and set their values by using parameters.
Edit:
In order to make the wizard create a parameter to use in the query, add a ? in the filter column in the query builder wizard.
Well, I may misunderstand, but...you are not actually sending the string 'Label1.Text' I guess? You should send the value of the textbox, something like this (if you are building the SQL as a string?):
...[SQL]... + "c.customer_id = '"+ Label1.Text + "'" ...[rest of the SQL]

Resources