I am to be unable to get the following code to work. I know how to use python variables in queries, but somehow I can't get this right. The query works fine when I hard code the 'icaocode' variable in the query, but not if I try to use a variable. What is wrong with this code?
icaocode = input()
c.execute("SELECT EXISTS(SELECT 1 FROM airports WHERE ICAO = ?)", (icaocode))
if c.fetchone():
print("Found!")
else:
print("Not found...")
Received error:
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 4 supplied.
In Python, wrapping an expression in parentheses does not make any difference, (icaocode) is exactly the same as icaocode.
The execute method expects some kind of list of parameters, so it sees the string as a sequence of four characters.
To tell Python that you want a tuple with a single element, you have to add a comma:
c.execute("... WHERE ICAO = ?", (icaocode,))
Related
Is there any reason that this syntax shouldn't work in Qlikview load script??
Let v_myNumber = year(today());
Let v_myString = '2017-08';
If left($(v_myString),4) = text($(v_myNumber)) Then
'do something
Else
'do something else
End If;
I've tried both ways where I convert variable string to number and evaluate against the number variable directly and this way. They won't evaluate to equivalence when they should..
Left function is expecting a string as is getting something else as a parameter. As you are currently doing, the function will be called as Left(2017-08, 4) which is unhandle by QlikView.
If you use Left('$(v_myString)',4), it will evaluate as Left('2017-08', 4) as work as expected. Just adding quotes around the variable it should work.
Although QlikView calls them variables, they should really be seen as "stuff to replaced (at sometimes evaluated) at runtime", which is slightly different from a standard "variable" behaviour.
Dollar sign expansion is a big subject, but in short:
if you are setting a variable - no need for $().
if you are using a variable - you can use $(). depends on its context.
if you are using a variable that needs to be evaluated - you have to use $().
for example in a load script: let var1 = 'if(a=1,1,2)' - here later on the script you will probably want to use this variable as $(var1) so it will be evaluated on the fly...
I hope its a little more clear now. variable can be used in many ways at even can take parameters!
for example:
var2 = $1*$2
and then you can use like this: $(var2(2,3)) which will yield 6
For further exploration of this, I would suggest reading this
This error showed up when I was trying to search from a range of date.
This is my model:
def self.search(search)
if search
#policies = Policy.find_by_sql("acct_ent_date IN ?", start_date..end_date)
else
limit(10)
end
end
Just to help out anyone else coming here: If you want to use query params with find_by_sql, you need to put all the arguments into an array, like this:
Policy.find_by_sql(["acct_ent_date IN ?", start_date..end_date])
I've never actually seen passing a range as a query parameter, so I can't comment on that, but in general the "undefined method `value_for_database'" error comes from not wrapping the arguments in an array.
You rarely need to drop down to writing raw SQL in rails (e.g. using the find_by_sql method) - especially for such a simple query as this.
Instead, you can just write the following and ActiveRecord will correctly convert it to valid SQL syntax for you:
# If you are looking for a list of all matching entries:
Policy.where(acct_ent_date: start_date..end_date)
# If you only wish to fetch the FIRST matching entry:
Policy.find_by(acct_ent_date: start_date..end_date)
This will generate SQL like the following:
SELECT `policies`.* FROM `policies` WHERE (`policies`.`acct_ent_date` BETWEEN xxxxx AND yyyyy)
The key problem with your original (raw SQL) code is that you are using WHERE IN syntax - which is really just shorthand for multiple OR conditions. This does not make sense to use with a Range (start_date..end_date) object, as this is not a discrete list (i.e. an Array).
If you were to attempt to convert your object into an array, you would see an error something like this:
(start_date..end_date).to_a # => TypeError: can't iterate from Time
In my Rails application I need to check if an object exists and if it does, I need to assign the latitude and longitude attributes of that object to two external variables named latitude and longitude.
my controller code
def query
if ( Coordinates.where(city :params[:show]).exists?) equal? 1) then
a=Coordinates.where(city: params[:show])
latitude=a.latitude
longitude=a.longitude
end
But When I run the program In the browser I am getting syntax error despite I tried several times changing the syntax The error I am getting is "syntax error, unexpected tFID, expecting keyword_then or ';' or '\n'". Anybody please help me how to solve this problem ,thanks in advance
I've got several remarks:
in Ruby the syntax for an if is generally (without then)
if condition
code
end
where returns a ActiveRecord Association, thus it is a collection so you can't call a.latitude for example. Try Coordinates.where(city: params[:show]).first or something like that.
have you defined a method called equal?? If not there is at least a . missing.
The if statement is more or less useless.
def query
a = Coordinates.where(city: params[:show])
b = a.first
if a.count == 1
latitude = b.latitude
longitude= b.longitude
else
# do something else
end
end
This line seems to be the problem:
( Coordinates.where(city :params[:show]).exists?) equal? 1)
What exactly do you want to know? In this case it might be better to explain it to us in words, because your code seems confusing. Ayonix has a working example of the query method, but I'm not sure if that method describes exactly what you want to know.
I tested this query in my database, and it works fine:
select * from variables where value = 'commas-:-)';
I get a result. Now, I stored the value in a variable and use the query class.
$value = 'commas-:-)' <<< this is passed as a parameter
$query = "select * from variables where value = '$value'";
$this->db->query($query);
Now, this query works for every other value except for this one - but what's odd is that if I PRINT out the exact query (print_r of $query) and execute it on the database, it returns the correct result. So I'm left to think that the query class is screwing with my query, which it shouldn't because everything is properly escaped and $value is a string literal.
What is going on?
$sql = "SELECT * FROM variables WHERE value = ?";
$this->db->query($sql, array('commas-:-)'));
More info
$get_data = $this->db->from('variables')
->where('value', $value)
->get();
Hope this will work...!
try to use these things for checking the queries
echo $this->db->last_query();
print_r($this->db->result_array($get_data));
I found the issue - it was the rerouting function that was causing the mishap. More specifically, the segment filtering function within the route folder in the system core.
This is what happened:
I created an anchor with the encoded value (commas:-)) and I configured the route to reroute the uri to a function I had in my controller. Each time I clicked the link, the value gets passed, and (supposedly) rerouted to the function. Which it did, for almost all the values I used. Except this one.
1st assumption: the db query function is escaping the values. But I turned off the escape, as well as checked the query by printing. The value was correct. I then tried other query formats, and still no results. Conclusion: There's nothing wrong with the database query functions.
2nd assumption: the data must be corrupt - although the value is correct (I'm getting commas:-)), it's not returning anything except when I type in the value manually. So I tested this:
I created a seperate value, and set it equals to the one I typed in(the one that works). I then printed the original value(one passed) and the newly created value using VAR_DUMP.
Turns out, the argument value (one that doesn't work) is a string with length 14 whereas my new variable was a string with a length of 10. WTF? Conclusion: Something occured during the rerouting / passing process that changed the variable.
I went back to the config folder, and replace the variable $i in the reroute to the literal string value commas:-). And guess what? It worked perfectly. And just to make sure it wasn't the regex, I wrote my own custom regex and it matched fine, but the value was still being changed. So I decided to get under the hood.
I traced the URI manipulation in the routes class to the _explode_segment() function, which was used to perform the regex and analyse the uri for other variables. It also did this thing ...
_filter_uri($str)
for each part of the uri segment that was matched.
What did it do? It replaces programmable characters like ( and ) with their HTML ENTITY. Now, if you don't know, html entities have long lengths than url encoding. LOL. So what happened was this:
Original segment : commas-%3A-%29 <- very nice!
Filtered segment : commas-%3A-) <- NOOOOOOOOO! (the right paren encoded with ).)
urldecode(")") = string(4)
urldecode("%29") = string(1)
Fail.
or WIN?!
Alright, I'm trying to query a sqlite database. I was trying to be good and use the query method of SQLiteDatabase and pass in the values in the selectArgs parameter to ensure everything got properly escaped, but it wouldn't work. I never got any rows returned (no errors, either).
I started getting curious about the SQL that this generated so I did some more poking around and found SQLiteQueryBuilder (and apparently Stack Overflow doesn't handle links with parentheses in them well, so I can't link to the anchor for the buildQuery method), which I assume uses the same logic to generate the SQL statement. I did this:
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables(BarcodeDb.Barcodes.TABLE_NAME);
String sql = builder.buildQuery(new String[] { BarcodeDb.Barcodes.ID, BarcodeDb.Barcodes.TIMESTAMP, BarcodeDb.Barcodes.TYPE, BarcodeDb.Barcodes.VALUE },
"? = '?' AND ? = '?'",
new String[] { BarcodeDb.Barcodes.VALUE, barcode.getValue(), BarcodeDb.Barcodes.TYPE, barcode.getType()},
null, null, null, null);
Log.d(tag, "Query is: " + sql);
The SQL that gets logged at this point is:
SELECT _id, timestamp, type, value FROM barcodes WHERE (? = '?' AND ? = '?')
However, here's what the documentation for SQLiteQueryBuilder.buildQuery says about the selectAgs parameter:
You may include ?s in selection, which
will be replaced by the values from
selectionArgs, in order that they
appear in the selection.
...but it isn't working. Any ideas?
The doc for SQLiteQueryBuilder.buildQuery also says, "The values will be bound as Strings." This tells me that it is doing the straight-forward thing, which is writing the SQL leaving the ? parameter markers in place, which is what you are seeing, and binding the selectArgs as input parameters.
The ? are replaced by sqlite when it runs the query, not in the SQL string. The first string in the array will go where you see the first ?, and so on, when the query actually executes. I would expect the logged SQL to still have the ? markers.
Probably, your query fails because you are quoting the ?. For example, don't use WHERE ID = '?', just use WHERE ID = ?, and make sure the selectArgs is a string that satisfies the query.
Two things:
The ? substitution will not be done at this point, but only when the query is executed by the SQLiteDatabase.
From what I've seen, ? substitution only works for the right side of comparison clauses. For example, some people have tried to use ? for the table name, which blows up. I haven't seen anyone try using ? for the left side of the comparison clause, so it might work -- I'm just warning you that it might not.