I found it really cool that in Groovy SQL it is possible to do this:
def resultList = Domain.executeQuery('select * from languages where name = :name', [name: 'Groovy'])
I am trying to get the HQL "in" keyword to work with a dynamic list used as the argument, not a fixed list.
I also know that you can use the "?" operator for your SQL parameters instead of using named parameters. However according to this question:
Doing an "IN" query with Hibernate
The "in" keyword only supports named and positional parameters, not the "?" parameter. The problem is, when I try to do something like this:
def paramMap = [:]
paramMap.put("name", "groovy")
def resultList = Domain.executeQuery('select * from languages where name = :name', paramMap)
I get an error saying that I have not specified the parameter name. So it is acting as if I have not actually specified the parameter "name". I have read the Groovy documentation on named parameters here:
http://groovy.codehaus.org/api/groovy/sql/Sql.html
But all of the examples using named parameters use a predefined parameter list. I have searched and have not found an example of using a dynamic parameter list map. How can I pass a dynamic map of parameters into Groovy named SQL query? If that is not possible, how can I use the "in" keyword with a dynamic list?
To be clear, I am constructing a dynamic SQL query and I would like to be able to add parameters to a map or list as I go along. I was previously using the "?" operator until I had to use the "in" clause, which does not work with "?".
Why not try find all with closures?
def paramMap = [:]
paramMap.put("name", "groovy")
def resultList = Domain.findAll {
paramMap.containsValue(name)
}
Here's the docs, hopefully it helps! http://grails.org/doc/latest/ref/Domain%20Classes/findAll.html
Related
I am trying to run a select by attribute where I select all points where "Id" field matches the numeric variable point_id. point_id = 375.
I've tried a few quotation styles and using curly brackets to call my variable. I'm not the most familiar with SQL queries and get an error saying the positional argument follows the keyword string. I have also tried storing my SQL as a variable on it's own called a whereClause and get the same error.
First attempt code
arcpy.management.SelectLayerByAttribute(in_layer_or_view = deer,
selection_type = "NEW_SELECTION",
f'"Id"={point_id}')
Second attempt code
The is a Python issue, not related to ArcGIS or SQL.
You are trying to pass three arguments. For the first two arguments you're using keyword argument (explicitly specifying the argument name: in_layer_or_view = deer), but for the third one you're using positional argument (letting python assign the value to the appropriate argument based on the order of the arguments).
The execption you're getting is telling you that you can't mix the two types this way. Once you started using keyword arguments in the function call, all of the next argument must be passed with their explicit name too.
To fix this, you can use positional argument for all of the arguments (i.e. not specifing argument names at all), or alternatively keep specifing the names for all of the rest of the arguments.
In your case, this should work:
arcpy.management.SelectLayerByAttribute(in_layer_or_view=deer,
selection_type="NEW_SELECTION",
where_clause=f'"Id"={point_id}')
or alternatively:
arcpy.management.SelectLayerByAttribute(deer,
"NEW_SELECTION",
f'"Id"={point_id}')
I have a simple SQL statement query that is executed as command from C# code. It is targetting DB2. I created variables for the server/schemas as follows. It throws error.
private const string DB2Query
= #"SELECT Name as Name FROM {Schema}.Application WHERE ID = ?";
I get this error.
ERROR [37000] [IBM][CLI Driver] CLI0118E Invalid SQL syntax. SQLSTATE=37000
However, I don't get that error when executing from SQL as follows:
SELECT Name as Name
FROM MyServer..FOR3.Application
WHERE ID = 'MOM'
To support this, I tried to also do something like below in code, still throws different error.
private const string DB2Query
= #"SELECT Name as Name FROM {ServerName}..{Schema}.Application WHERE ID = ?";
It throws error on this line of code:
DataApplicationBlockHelper<string>.Get(db, dbCommand, Obj);
UPDATE
I found the culprit. It's not replacing the {Schema} placeholder. When I actually removed that from query and placed the schema name, it worked like a charm. It's a .net thing I believe? Can someone please help how to replace {Schema} with a value fetched from web.config?
While I can't really speak to the syntax of DB2 queries themselves, so I'll rely on your assertion that the query itself should work...
What you have in C# is simply a string and nothing more:
private const string DB2Query = #"SELECT Name as Name FROM {Schema}.Application WHERE ID = ?";
Note that there's no need for the # operator in this string definition, so let's simplify:
private const string DB2Query = "SELECT Name as Name FROM {Schema}.Application WHERE ID = ?";
While this string appears intuitively to have a placeholder that can be replaced with a value, if there's no code which does that anywhere then it won't happen. For that you have a few options. For example, you can use a placeholder that string.Format() understands:
private const string DB2Query = "SELECT Name as Name FROM {0}.Application WHERE ID = ?";
And then later in a method somewhere, when you want to use that string, apply the format value to it:
var sql = string.Format(DB2Query, someVariable);
In this case someVariable (which doesn't even need to be a variable and could be a string literal) would be used to replace the placeholder in the string.
Or, if you want to keep the named placeholder, you can potentially replace it manually:
private const string DB2Query = "SELECT Name as Name FROM {Schema}.Application WHERE ID = ?";
and later in a method:
var sql = DB2Query.Replace("{Schema}", someVariable);
This would observably accomplish the same thing, perhaps with an extremely minor performance difference.
You could also take advantage of both approaches by using the more recent language feature of string interpolation. This would use the $ operator to apply format placeholders in place directly. I don't think you can use this in a const, it's more for a local variable. Something like this:
var sql = $"SELECT Name as Name FROM {someVariable}.Application WHERE ID = ?";
This would still perform the same replacement, putting someVariable where the placeholder is, it's just using a more concise syntax than a call to string.Format(). One thing to note about this syntax is that it makes it look more like this interpolation is happening directly in-place on the string. It's still a multi-step process behind the scenes, which is why it likely won't work on a const or on class members at all (and should I imagine produce a compiler error).
Remember that strings are immutable, so any operation you perform which modifies a string would be returning a new string rather than modifying the existing one in place.
In any case, you'll of course also need to apply your query parameter for the ? placeholder. Note that what C# considers to be a placeholder in a string formatting/interpolating operation and what DB2 considers to be a placeholder for a query parameter are two entirely different things which happen at different times in different environments. (One in the .NET runtime, one in the database server's query execution.) But again, I'm relying on your assertion that the database query itself works and the only problem we're focusing on here is the C# string placeholder.
I'm trying to access a FlowVar name dynamically in DataWeave.
For example:
I have a flowVars named taxInfo123. This is a linked list and my applicant.ApplicantID = 123
In my dataweave, I want to access this dynamically. Something like the following:
"TaxInfo": flowVars.'taxInfo'+applicant.ApplicantID map ((taxIdentificationDetail , indexOfTaxIdentificationDetail) -> {
This obviously doesn't work, and I'm hoping this is possible and I just need the correct syntax.
If you need to dynamically create the variable name, you can use the flowVars[key] syntax instead of the flowVars.key syntax. In your scenario:
"TaxInfo": flowVars[('taxInfo' ++ (flowVars.applicant.ApplicantID as :string))]
I assumed applicant was also a flowVar but you could just as easily use payload.applicant.ApplicantID or whatever your situation calls for. I also assumed it was a number so I had to cast it as a string.
When you use this syntax you want to make sure you wrap the key expression in parenthesis so it is evaluated first and then the flowVar is resolved.
So to summarize:
If you know the variable name is 'taxInfo123' -
flowVars.taxInfo123 or flowVars[taxInfo123] are both valid
If you need to create the variable name dynamically -
flowVars[(expression)]
Hope that helps!
Forming the variable name needs append operator like ++. Please go through the MuleSoft documentation for Dataweave operators to get better understanding of how much flexiblity is possible in Dataweave.
https://docs.mulesoft.com/mule-user-guide/v/3.8/dataweave-operators
In one of our application the parameters passed to a stored procedure in this way
Dim parm As New SqlParameter("searchText", SqlDbType.VarChar)
parm.Direction = ParameterDirection.Input
parm.Size = 50
parm.Value="test"
cmd.Parameters.Add(parm)
and the procedure contains a parameter as #searchText
i.e. the parameter name passed from the code is searchText and that in the stored procedure is #searchText .
But it is working properly, I am always getting the required results.
So my question is like so there is no need to specify # before the parameter? Whether it will append #, can anyone please give an answer for this.
According to the documentation, the name must start with an #:
The ParameterName is specified in the form #paramname.
According to the source code (have a look at SqlCommand and SqlParameter.ParameterNameFixed in the reference source), an # is added automatically, if needed.
So yes, it works, but it's an undocumented feature. Best practice recommends that you do not rely on this and manually prefix your parameter name with an #.
Ref: SqlParameter.ParameterName Property and IDataParameter.ParameterName Property
The ParameterName is specified in the form #paramname. You must set ParameterName before executing a SqlCommand that relies on parameters. If you are using Sql Server as Database then you must specify # before
the parameter name.
your parameter name must be same as at backend eg. you have #searchText then in your parameter specification it must be SqlParameter("#searchText" ..
your code should be like this
Dim parm As New SqlParameter("#searchText", SqlDbType.VarChar)
parm.Direction = ParameterDirection.Input
parm.Size = 50
parm.Value="test"
cmd.Parameters.Add(parm)
Note: Oracle and SqLite use different use different character to specify parameter and there may be # symbol is not used specified by the specification of ado.net.
Edit: By comments
As you specified the link, it is also some sort of fix, but as per the msdn documentation, you must specify the positional parameter with '#' whether you are using any data provider oledb, sql, odbc. Ref
if (0 < parameterName.get_Length() && '#' != parameterName.get_Chars(0))
{
parameterName = "#" + parameterName;
}
Its not compulsory to specify the #. However, its a best practice.
Its similar in analogy to strings. There certainly is no harm in defining strings as such in .NET:
string s;
//Rest of the code follows;
But again, its a best practice to define them as :
string s = string.Empty;
You see, its a question of conventions and best practices!!!
I recommended you to use add "#" marker with your parameter name.
SqlParameter helps to add automatically, but others' parameter might not to.
Is the "#" symbol required? Yes and No. When you add a parameter using DbCommand, it's optional regardless of whether you're using SQL Server or not:
// Look Ma no # required!
DbCommand command = database.GetStoredProcCommand("StoredProctologistAndGambler");
database.AddInParameter(command, "Bet", DbType.Int32, fromLineNumber);
database.AddOutParameter(command, "Diagnosis", DbType.String, -1);
If you're going to reference the command later, however, the "#" prefix is required. Microsoft figured it was to hard to carry it over to the rest of the API.
var examResult = command.Parameters["#Diagnosis"]; // Ma! Microsoft lied! It requires the "#" prefix.
i have a populated list:
def someList=... (string values)
and I want to pass this into a SQL statement to restrict which columns the query selects.
db.rows("select ${someList} from arch_application")
However, I get this error when I try to do so:
There is a ? parameter in the select list. This is not allowed.
Anyone have an ideas? Thanks!
When you pass a GString to Sql.rows, it gets parsed differently than normal in groovy. In particular, it creates a PreparedStatement with replaceable parameters for ${} substitutions. In your case this is probably not what you want. Try forcing the GString to a Java string:
db.rows("select ${someList.join(',')} from arch_application" as String)