I am trying to make a sql query and input that into a variable called tid. This is using the ruby on rails language where I am trying to attempt with the bottom code.
#test = Customer.where(:email => #email).first tid = #test[:id]
Moreover, it gives me a 500 Internal Error saying "Action Controller: Exception caught"
Thank you in advance
Your #test should be a Customer object or nil, not a Hash. You should try:
tid = #test.try(:id)
That will give you the Customer ID or nil in tid.
Related
Good Morning everyone, after lookin everwhere, i come to you to ask for a help.
So i have a this mysql query
SELECT * FROM USER WHERE WORPLACE ='TECHNICIAN',
And here is my JQPL query
SELECT U FROM USER U WHERE U.WORPLACE =:+TECHNICIAN
But some how i get this error on Glassfish
java.lang.IllegalStateException: Query argument Technician not found in the list of parameters provided during query execution.
Here is the code of my arraylist on the managed Bean
public List<Users> getListUsers() {
return this.userService.getTechnicians("Technician");
}
So, what do i want specificlly. I want a query that can sort in a table list of user where there workplace are 'Technician'.
Thanks for your help and have a nice day.
In JPQL named query parameters start with a : followed by the name. So, if you want to call your query parameter Technician you need to reference it as :Technician in your query.
You can then call the setParameter method on the Query interface with the parameter name and its value.
Here's an example using your query:
public List<User> getTechnicians(String technician) {
TypedQuery<User> q = getEntityManager().createQuery("SELECT u FROM User u WHERE u.poste =:Technician", User.class );
q.setParameter("Technician", technician);
return q.getResultList();
}
I do not know what I am doing wrong here? Can someone please help me? When the following query is executed in Drupal7 custom module, I get the following error:
ERROR:
ResponseText: PDOException: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens:
SELECT t.tid AS tid, t.name AS name
FROM
{taxonomy_term_data} t
WHERE (t.vid = :vid) AND (LOWER(t.name) LIKE LOWER('%%:last_string%%'))
LIMIT 50 OFFSET 0;
Array
(
[:vid] => 6
[:last_string] => server
)
CODE:
$result = db_select('taxonomy_term_data', 't')
->fields('t', array('tid', 'name'))
->where('t.vid = :vid', array(':vid'=>$vid))
->where("LOWER(t.name) LIKE LOWER('%%:last_string%%')", array(':last_string'=>$last_string))
->range(0, $num_results)
->execute();
The query works if I directly hard code the value for :last_string,
Example:
->where("LOWER(t.name) LIKE LOWER('%%server%%')")
any help is much appreciated..
Try using only one % because: % is a substitute for zero or more characters. You don't need 2 of them.
The LOWER function takes a string as parameter and '%:last_string%' is taken as string not as a binding to the array(':last_string'=>$last_string), that's why it works when you remove the binding. So try to not put :last_string inside the LOWER function because it won't recognize it as a binding.
INSERT INTO voucher (voucher_no, account, party_name, rece_amt, particulars, voucher_date, voucher_type, cuid, cdt)
SELECT voucher_rec_no, #account, #party_name, #rece_amt, #particulars, #voucher_date, #voucher_type, #cuid, #cdt
FROM auto_number
WHERE (auto_no = 1)
Error:
A parameter is not allowed in this location. Ensure that the '#' sign is in a valid location or that parameters are valid at all in this SQL statement.
I've just stumbled upon this whilst trying to fix the same issue. I know it's late but, assuming that you're getting this error when attempting to execute the query via .net, ensure that you are setting the SqlCeParameter.DbType - if this is not specified, you get the exception you listed above.
Example (assume cmd is a SqlCeCommand - all the stuff is in the System.Data.SqlServerCe namespace):
SqlCeParameter param = new SqlCeParameter();
param.ParameterName = "#SomeParameterName";
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String; // this is the important bit to avoid the exception
param.Value = kvp.Value;
cmd.Parameters.Add(param);
Obviously, you'd want to set the DB type to match the type of your parameter.
I am new to R and I am trying to do something that feels simple but cant get my code to work.
When I run my code (sqlQuery and which saves the data to a SQL database) it works fine with the database name but when I use an object as the database name instead of the actual name I get the following error -Error in if (errors) return(odbcGetErrMsg(channel)) else return(invisible(stat)) :argument is not interpretable as logical
The way I am using the object name in my R code is for example is select * from ",object,".dbo.tstTable The object dataBase is the date of every previous Friday.
StartCode(Server = "Server01",DB=dataBase,WH=FALSE) POLICYLIST <- sqlQuery(channel1," SELECT DISTINCT [POLICY_ID] FROM ",dataBase,".[dbo].[policy] ") StartCode(Server = "SERVER02",DB="DataQuality",WH=FALSE) sqlQuery(channel1,"drop table DQ1") sqlSave (channel1, POLICYLIST, "DQ1")
Finally figured out why my code was not working I changed my code to the below to make it work. I just needed to add paste. appologies for my stupid question!
StartCode(Server = "Server01",DB=dataBase,WH=FALSE) POLICYLIST <- sqlQuery(channel1, paste" SELECT DISTINCT [POLICY_ID] FROM ",dataBase,".[dbo].[policy] ")) StartCode(Server = "SERVER02",DB="DataQuality",WH=FALSE) sqlQuery(channel1,"drop table DQ1") sqlSave (channel1, POLICYLIST, "DQ1")
I've been trying to figure out how to pass the request.args to sqlalchemy filter.
I thought this should work:
model.query.filter(**request.args).all()
But it's throwing the error:
TypeError: <lambda>() got an unexpected keyword argument 'userid'
When userid or any other get arg is present.
According to this post - https://stackoverflow.com/questions/19506105/flask-sqlalchemy-query-with-keyword-as-variable - you can pass a dict to the filter function.
Any ideas what I'm doing wrong?
Many thanks :)
UPDATE: Many thanks to the poster below, however now it's throwing the following error:
ProgrammingError: (ProgrammingError) (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') ORDER BY tblclients.clientname' at line 3") 'SELECT favourites.id AS favourites_id, favourites.userid AS favourites_userid, favourites.clientid AS favourites_clientid, favourites.last_visit AS favourites_last_visit \nFROM favourites INNER JOIN tblclients ON tblclients.clientid = favourites.clientid \nWHERE favourites.userid = %s ORDER BY tblclients.clientname' ([u'41'],)
Any ideas?
First, you have to use filter_by, not filter.
Second, Flask request.args uses a MultiDict, a dict with the values inside a list, allowing more than one value for the same key, because the same field can appear more than once in a querystring. You got the error because the SQL query got the [u'41'] when it expected only '41'. You can use request.args.to_dict() to fix that:
model.query.filter_by(**request.args.to_dict()).all()
Use filter_by:
model.query.filter_by(**request.args).all()
filter is used like this: query.filter(Class.property == value) while filter_by is used like this: query.filter_by(property=value) (the first one being an expression and the latter one being a keyword argument).
filter_by(**request.args) doesn't work well if you have non-model query parameters, like page for pagination, otherwise you get errors like these:
InvalidRequestError: Entity '<class 'flask_sqlalchemy.JobSerializable'>' has no property 'page'
I use something like this which ignores query parameters not in the model:
builder = MyModel.query
for key in request.args:
if hasattr(MyModel, key):
vals = request.args.getlist(key) # one or many
builder = builder.filter(getattr(MyModel, key).in_(vals))
if not 'page' in request.args:
resources = builder.all()
else:
resources = builder.paginate(
int(request.args['page'])).items
Considering a model with a column called valid, something like this will work:
curl -XGET "http://0.0.0.0/mymodel_endpoint?page=1&valid=2&invalid=whatever&valid=1"
invalid will be ignored, and page is available for pagination and best of all, the following SQL will be generated: WHERE mymodel.valid in (1,2)
(get the above snippet for free if you use this boilerplate-saving module)
You can:
http://localhost:5000/filter-test?var=test
query_dict = request.args.to_dict()
print(query_dict)
{'var': 'test'}
print(query_dict['var'])
var