Objective-C Strings - objective-c

I am reviewing code that makes the following call:
id<PLResultSet> results = [sqliteDatabase executeQuery:#"select * where id=?",Id];
sqliteDatabase is an instance of PlausibleDatabase (from GoogleCode, I gather). The code works, but I don't understand it. Specifically, how does this section work?
#"select * where id=?",Id
Is the query being made with ? being replaced by Id? Or is the exeuteQuery function somehow combining the strings? How does this syntax make sense.
(Yes, I am new to Obj-C)
Thanks,
KF

This bit:
#"select * where id=?"
is an NSString (as opposed to a c-style string) which is being passed into a executeQuery: : method on the sqliteDatabase object. The second (unnamed) argument to the method is Id, presumably a local variable.
Guessing from the name of the method, the sqlite wrapper probably creates a parameterized query. The question mark is the syntax used by sqlite to mark where to insert the parameters.

It's specific to the method executeQuery, in which ? is used as a placeholder, and the appropriate positional argument is used as filler for that placeholder (with quoting, etc. added as necessary).

Related

ERROR [37000] [IBM][CLI Driver] CLI0118E Invalid SQL syntax. SQLSTATE=37000

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.

Pass Java List to SQL query Grails

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)

Methods with multiple arguments in objective C

If you take this method call for instance(from other post)
- (int)methodName:(int)arg1 withArg2:(int)arg2
{
// Do something crazy!
return someInt;
}
Is withArg2 actually ever used for anything inside this method ?
withArg2 is part of the method name (it is usually written without arguments as methodName:withArg2: if you want to refer to the method in the documentation), so no, it is not used for anything inside the method.
As Tamás points out, withArg2 is part of the method name. If you write a function with the exact same name in C, it will look like this:
int methodNamewithArg2(int arg1, int arg2)
{
// Do something crazy!
return someInt;
}
Coming from other programming languages, the Objective-C syntax at first might appear weird, but after a while you will start to understand how it makes your whole code more expressive. If you see the following C++ function call:
anObject.subString("foobar", 2, 3, true);
and compare it to a similar Objective-C method invocation
[anObject subString:"foobar" startingAtCharacter:2 numberOfCharacters:3 makeResultUpperCase:YES];
it should become clear what I mean. The example may be contrived, but the point is to show that embedding the meaning of the next parameter into the method name allows to write very readable code. Even if you choose horrible variable names or use literals (as in the example above), you will still be able to make sense of the code without having to look up the method documentation.
You would call this method as follows:
int i=[self methodName:arg1 withArg2:arg2];
This is just iOs's way of making the code easier to read.

Cpp . NET: "a->Methodname " vs "a.MethodName"

I would like to know the difference between these two (sorry I do not know the name of this subject).
I come from C# where I was used to write System.data as well as classA.MethodA. I have already found out that in Cpp, with namespaces I need to use ::, with classmembers ->. But what about simple "."?
I have created System::data:odbc::odbcConnection^ connection. Later I was able to use connection.Open. Why not connection->open?
Im sorry, I am sure its something easily findable on the net, but I dont know english term for these.
Thank you guys
If you have a pointer to an object, you use:
MyClass *a = new MyClass();
a->MethodName();
On the other hand, if you have an actual object, you use dotted notation:
MyClass a;
a.MethodName();
To clarify the previous answers slightly, the caret character ^ in VC++ can be thought of as a * for most intents and purposes. It is a 'handle' to a class, and means something slightly different, but similar. See this short Googled explanation:
http://blogs.msdn.com/branbray/archive/2003/11/17/51016.aspx
So, in your example there, if you initialize your connection like:
System::Data::Odbc::OdbcConnection connect;
//You should be able to do this:
connect.Open();
Conversely, if you do this:
System::Data::Odbc::OdbcConnection^ connect1 = gcnew System::Data::Odbc::OdbcConnection();
connect1.Open(); // should be an error
connect1->Open(); //correct
The short answer: C++ allows you to manage your own memory. As such, you can create and manipulate memory, through usage of pointers (essentially integer variables containing memory addresses, rather than a value).
a.Method() means a is an instance of a class, from which you call Method.
a->Method() means a is a pointer to an instance of a class, from which you call Method.
When you use syntax like a->member, you are using a pointer to a structure or object.
When you use syntax like a.member, you are using the structure or object and not a pointer to the structure or object.
I did a quick google for you and THIS looks fairly quick and decent explanation.

What is the definition of ":=" in vb

I came across some sample code in VB.Net which I have some experience with and kinda having a duh moment figuring out the meaning of :=.
RefreshNavigationImages(bForward:=True, startIndex:=-1)
The sig for this method is RefreshNavigationImages(boolean, int). Is this a default value if null? Like "bIsSomething ?? false"?
Tried to bing/google but they just don't like searching for operators especially if it's only 2 chars.
They are named parameters. They let you specify values for arguments in function calls by name rather than order.
The := indicates the use of named parameters. Rather than relying on the order of the parameters in the method declaration, named parameters allow you to specify the correlation of parameters to values by specifying the name of the parameter.