private static String XXX = "{call SP_XXX(?,?,?)}"
sql.call (XXX, [Sql.NUMERIC, Sql.NUMERIC,'SOME STRING'){
outPara1, outPara2 ->
log.info("${outPara1}, ${outPara2}")
}
I am able to call the stored procedure successful with the above code.
But, when I am using named parameters instead of '?' placeholder.
I am getting:
WARNING: Failed to execute: {call SP_XXX(:OUTP1, :OUTP2, :INP1)}
because: Invalid column type
What I changed is replaced the '?' with ":OUTP1", "OUTP2" and ":INP1".
And in the call statement, using the named parameters accordingly.
The code after change:
private static String XXX = "{call SP_XXX(:OUTP1, :OUTP2, :INP1)}"
sql.call (XXX, [OUTP1: Sql.NUMERIC, OUTP2: Sql.NUMERIC, INP1: 'SOME STRING']){
outPara1, outPara2 ->
log.info("${outPara1}, ${outPara2}")
}
What you are doing is passing a map to call() which I do not think we have an api for. Moreover, the placeholders for the SP has to be ?.
Either you can stick to your former approach or try using GString as below:
def inp1 = 'SOME STRING'
sql.call "{call SP_XXX(${Sql.NUMERIC}, ${Sql.NUMERIC}, $inp1)}", {
outPara1, outPara2 ->
log.info("${outPara1}, ${outPara2}")
}
I would prefer the former approach instead. :-)
Related
I found this SQLHelper online that I would like to run a SQL query with.
But the helper wants an list instead of an string.
and I cannot seem to figure out how to make the executeNonQuery to work.
type SqlHelper (connection) =
let exec bind parametres query =
use conn = new SqlConnection (connection)
conn.Open()
use cmd = new SqlCommand (query, conn)
parametres |> List.iteri (fun i p ->
cmd.Parameters.AddWithValue(sprintf "#p%d" i, box p) |> ignore)
bind cmd
member __.Execute = exec <| fun c -> c.ExecuteNonQuery() |> ignore
member __.Scalar = exec <| fun c -> c.ExecuteScalar()
member __.Read f = exec <| fun c -> [ let read = c.ExecuteReader()
while read.Read() do
yield f read ]
let sql = new SqlHelper (connectionString)
The query I have is for dopping the tables
and I'm trying to execute like this.
let emptyDb =
let query =
"SET NOCOUNT ON
DROP TABLE IF EXISTS #STUFF
...
...
END"
sql.Execute [query ]
This compiles, but nothing happens when I execute it.
Any ideas?
Thanks in advance
Edit: sql.Read function works perfect
let GetToken Id=
sql.Read (fun r -> { token = unbox r.[0] })
[Id;]
"SELECT Token
FROM [dbo].[Token]
WHERE id= 0"
GetToken "1337"
You are not providing enough parameters for sql.Execute.
Look closely:
exec takes three parameters - bind, parametres (btw, typo), and query
In the body of Execute you give it one parameter - bind
Therefore, the result of Execute is a function that still expects the other two parameters - parametres and query
But when you're calling sql.Execute, you're only giving it one parameter - [query], which will end up bound to parametres
Therefore, the result of calling sql.Execute [query] is yet another function, which still expects the final parameter to be provided before its body will be executed. In fact, if you pay close attention to compiler warnings, you will see that the compiler actually tells you as much:
This expression is a function value, i.e. is missing arguments. Its type is ...
To fix, provide the correct parameters. Judging by the little piece of your query that I can see, I assume that it's not supposed to have any parametres, so I'll put an empty list there:
sql.Execute [] query
I have written a code that reads a text file. The text files contain placeholders which I would like to replace. The substitution does not work this way and the string is printed with the placeholders. Here is the code that I have written for this:
class TestSub(val sub: Sub) {
fun create() = template()
fun template() = Files.newBufferedReader(ClassPathResource(templateId.location).file.toPath()).readText()
}
data class Sub(val name: String, val age: Int)
Here is the main function that tries to print the final string:
fun main(args: Array<String>) {
val sub = Sub("Prashant", 32)
println(TestSub(sub).create())
}
However, when, instead of reading a file, I use a String, the following code works (Replacing fun template())
fun template() = "<h1>Hello ${sub.name}. Your age is ${sub.age}</h1>"
Is there a way to make string Substitution work when reading the content of a file?
Kotlin does not support String templates from files. I.e. code like "some variable: $variable" gets compiled to "some variable: " + variable. String templates are handled at compile time, which means it does not work with text loaded from files, or if you do something else to get the String escaped into a raw form. Either way, it would, as danielspaniol mentioned, be a security threat.
That leaves three options:
String.format(str)
MessageFormat.format(str)
Creating a custom engine
I don't know what your file contains, but if it's the String you used in the template function, change it to:
<h1>Hello {0}. Your age is {1,integer}</h1>
This is for MessageFormat, which is my personal preference. If you use String.format, use %s instead, and the other appropriate formats.
Now, use that in MessageFormat.format:
val result = MessageFormat.format(theString, name, age);
Note that if you use MessageFormat, you'll need to escape ' as ''. See this.
String substitution using ${...} is part of the string literals syntax and works roughly like this
val a = 1
val b = "abc ${a} def" // gets translated to something like val b = "abc " + a + " def"
So there is no way for this to work when you load from a text file. This would also be a huge security risk as it would allow for arbitrary code execution.
However I assume that Kotlin has something like a sprintf function where you can have placeholders like %s in your string and you can replace them with values
Take a look here. It looks like the easiest way is to use String.format
You are looking for something similar to Kotlin String templates for raw Strings, where placeholders like $var or ${var} are substituted by values, but this functionality needs to be available at runtime (for text read from files).
Methods like String.format(str) or MessageFormat.format(str) use other formats than the notation with the dollar prefix of Kotlin String templates. For "Kotlin-like" placeholder substitution you could use the function below (which I developed for similar reasons). It supports placeholders as $var or ${var} as well as dollar escaping by ${'$'}
/**
* Returns a String in which placeholders (e.g. $var or ${var}) are replaced by the specified values.
* This function can be used for resolving templates at RUNTIME (e.g. for templates read from files).
*
* Example:
* "\$var1\${var2}".resolve(mapOf("var1" to "VAL1", "var2" to "VAL2"))
* returns VAL1VAL2
*/
fun String.resolve(values: Map<String, String>): String {
val result = StringBuilder()
val matcherSimple = "\\$([a-zA-Z_][a-zA-Z_0-9]*)" // simple placeholder e.g. $var
val matcherWithBraces = "\\$\\{([a-zA-Z_][a-zA-Z_0-9]*)}" // placeholder within braces e.g. ${var}
// match a placeholder (like $var or ${var}) or ${'$'} (escaped dollar)
val allMatches = Regex("$matcherSimple|$matcherWithBraces|\\\$\\{'(\\\$)'}").findAll(this)
var position = 0
allMatches.forEach {
val range = it.range
val placeholder = this.substring(range)
val variableName = it.groups.filterNotNull()[1].value
val newText =
if ("\${'\$'}" == placeholder) "$"
else values[variableName] ?: throw IllegalArgumentException("Could not resolve placeholder $placeholder")
result.append(this.substring(position, range.start)).append(newText)
position = range.last + 1
}
result.append(this.substring(position))
return result.toString()
}
String templates only work for compile-time Sting literals, while what u read from a file is generated at runtime.
What u need is a template engine, which can render templates with variables or models at runtime.
For simple cases, String.format or MessageFormat.format in Java would work.
And for complex cases, check thymeleaf, velocity and so on.
error message:
URI
/racetrack/readUserRole/index
Class
org.postgresql.util.PSQLException
Message
Can't infer the SQL type to use for an instance of org.codehaus.groovy.runtime.GStringImpl. Use setObject() with an explicit Types value to specify the type to use
code:
a="col01"
b="col${usercol}"
c="col${rolecol}"
sql.eachRow("select $a,$b,$c from read_csv where col01=? and col${usercol}!=? ", [file.name,""]) {
t="${it."$a"}"
i="${it."$b"}"
r="${it."$c"}"
t.getClass() == String
i.getClass()== String
r.getClass()== String
def list2=[t,i,r]
println list2
sql.execute('insert into read_user_role(version,roledata,textname,userdata)'+
'VALUES (0,?,?,?)', list2)
}
the problem occurred at insert statement as error message, so how i suppose to fix this sql type issue?
Use the static methods on the Sql class to wrap your variable into a type known to the database. For example, to wrap a GString as varchar, you can use:
import static groovy.sql.Sql.*
....
sql.eachRow("select * from foo where name = ${VARCHAR(myVar)}")
How can I call a stored procedure using Groovy?
How can I create a stored procedure from Grails project (as domain classes to create data base)?
An example of calling a FullName stored procedure which takes a param ('Sam' in the example) and returns a VARCHAR.
sql.call("{? = call FullName(?)}", [Sql.VARCHAR, 'Sam']) { name ->
assert name == 'Sam Pullara'
}
The same example again but with a GString variation:
def first = 'Sam'
sql.call("{$Sql.VARCHAR = call FullName($first)}") { name ->
assert name == 'Sam Pullara'
}
Here is an example of a stored procedure with an out parameter:
sql.call '{call Hemisphere(?, ?, ?)}', ['Guillaume', 'Laforge', Sql.VARCHAR], { dwells ->
println dwells // => Northern Hemisphere
}
Refer this.
I got this parameter:
$objDbCmd.Parameters.Add("#telephone", [System.Data.SqlDbType]::VarChar, 18) | Out-Null;
$objDbCmd.Parameters["#telephone"].Value = $objUser.Telephone;
Where the string $objUser.Telephone can be empty. If it's empty, how can I convert it to [DBNull]::Value?
I tried:
if ([string]:IsNullOrEmpty($objUser.Telephone)) { $objUser.Telephone = [DBNull]::Value };
But that gives me the error:
Exception calling "ExecuteNonQuery" with "0" argument(s): "Failed to convert parameter value from a ResultPropertyValueCollection to a String."
And if I convert it to a string, it inserts an empty string "", and not DBNull.
How can this be accomplished?
Thanks.
In PowerShell, you can treat null/empty strings as a boolean.
$x = $null
if ($x) { 'this wont print' }
$x = ""
if ($x) { 'this wont print' }
$x = "blah"
if ($x) { 'this will' }
So.... having said that you can do:
$Parameter.Value = $(if ($x) { $x } else { [DBNull]::Value })
But I'd much rather wrap this up in a function like:
function CatchNull([String]$x) {
if ($x) { $x } else { [DBNull]::Value }
}
I don't know about powershell, but in C# I would do something like this:
if ([string]::IsNullOrEmpty($objUser.Telephone))
{
$objDbCmd.Parameters["#telephone"].Value = [DBNull]::Value;
}
else
{
$objDbCmd.Parameters["#telephone"].Value = $objUser.Telephone;
}
Always append +"" at the end of db values...
$command.Parameters["#EmployeeType"].Value= $ADResult.EmployeeType + ""
Many years later, let me clarify:
Josh's answer shows a helpful simplification for testing strings for emptiness (relying on PowerShell's implicit to-Boolean conversion[1]), but it is unrelated to Tommy's (the OP's) problem.
Instead, the error message
"Failed to convert parameter value from a ResultPropertyValueCollection to a String."
implies that it is the non-null case that caused the problem, because $objDbCmd.Parameters["#telephone"].Value expects either a string value or [DBNull]::Value, whereas $objUser.Telephone is of type [ResultPropertyValueCollection], i.e. a collection of values.
Thus, in the non-null case, a string value must be assigned, which must be derived from the collection; one option is to take the first collection element's value, another would be to join all values with a separator to form a single string, using, e.g., [string]::Join(';', $objUser.Telephone) or, if joining the elements with spaces is acceptable (not a good idea with multiple phone numbers), simply with "$($objUser.Telephone)".[2]
Detecting an empty collection via [string]:IsNullOrEmpty() actually worked, despite the type mismatch, due to how PowerShell implicitly stringifies collections when passing a value to a [string] typed method parameter.[2]
Similarly, using implicit to-Boolean conversion works as expected with collections too: an empty collection evaluates to $false, a non-empty one to $true (as long as there are either at least two elements or the only element by itself would be considered $true[1])
Therefore, one solution is to use the first telephone number entry:
$objDbCmd.Parameters["#telephone"].Value = if ($objUser.Telephone) {
$objUser.Telephone[0].ToString() # use first entry
} else {
[DBNull]::Value
}
Note: If $objUser.Telephone[0] directly returns a [string], you can omit the .ToString() call.
In PowerShell v7+ you can alternatively shorten the statement via a ternary conditional:
$objDbCmd.Parameters["#telephone"].Value =
$objUser.Telephone ? $objUser.Telephone[0].ToString() : [DBNull]::Value
[1] For a comprehensive summary of PowerShell's automatic to-Boolean conversions, see the bottom section of this answer.
[2] When implicitly converting a collection to a string, PowerShell joins the stringified elements of a collection with a single space as the separator by default; you can override the separator with the automatic $OFS variable, but that is rarely done in practice; e.g., array 'foo', 'bar' is converted to 'foo bar'; note that this conversion does not apply when you call the collection's .ToString() method explicitly, but it does apply inside expandable (interpolating) strings, e.g., "$array".