show the full query using SQLQuery - mysql

how to show the full string of a query using SQLQuery. I tried to use getQueryString()
but it doesn't show the parameter values in the returned string.
any idea how to display the full query that will be executed on the MySQL DB server?
Query query = session.createSQLQuery(
"select * from stock s where s.stock_code = :stockCode")
.addEntity(Stock.class)
.setParameter("stockCode", "7277");
query.getQueryString();
// this will return "select * from stock s where s.stock_code = :stockCode"
// and I need "select * from stock s where s.stock_code = 7277"

You can enable logging of the following categories (using a log4j.properties file here):
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
Refer this :
Hibernate show real SQL
How to print a query string with parameter values when using Hibernate

Related

mysql query using python 3.6 (string variable is in single quotes)

I am new in python as well as mysql. I am having trouble in populating proper query statement for mysql.
sql = "SELECT * FROM Persons WHERE %s"
cur = db.cursor()
cur.execute(sql,(where,))
where is a string variable which creates a string for WHERE clause; this is the point of question. When I print this variable it give the following result:
Gender = True And IsLate = False
(without any quotes) but when I add this variable to the query to execute it, it adds single quotes around the string.
I used the command
print(cur.statement)
and it prints:
SELECT * FROM Persons WHERE 'Gender = True And IsLate = False'
After supplying parameter, it puts it within single quotes and query returns 0 rows.
I have worked around by concatenating the query statement and variable together and execute the string as query, that worked,
sql = sql + where
cur.execute(sql)
But I know that is not the professional way, as I have searched and found the professional way is to use parameterized query and use variable to store the condition(s) and supplying it at the execution of query.
Looking for advice, am I thinking the right way or otherwise?
The whole point of using parameter substitution in cursor.execute() is that it protects you from SQL injection. Each parameter is treated as a literal value, not substituted into the query and re-interpreted.
If you really want it to be interprted, you need to use string formatting or concatenation, as you discovered. But then you will have to be very careful in validating the input, because the user can supply extra SQL code that you may not have expected, and cause the query to malfunction.
What you should do is build the where string and parameter list dynamically.
where = []
params = []
if gender_supplied:
where.append('gender = %s')
params.append(gender)
if islate_supplied:
where.append*('islate = %s')
params.append(islate)
sql = 'select * from persons'
if where:
query = sql + ' where ' + ' and '.join(where)
else:
query = sql
cur.execute(query, params)

how to write raw like query in django2?

I was trying to develop a search application where a user can search and for my system requirement I need to avoid ORM query when I try to write this following raw query
q = request.POST.get('searchData')
if q:
titleInfo = Item.objects.raw("""select * from item where title like '%%s%'""", [q])
It gives me this error
ValueError at /test
unsupported format character ''' (0x27) at index 41
And if I remove the quotation
"""select * from item where title like %%s%"""
It gives me the following error
ValueError at /test
incomplete format
Where my query is working fine in MySQL database
I solve the problem like this
q = request.POST.get('searchData')
query = '%'+q+'%'
if q:
titleInfo = Item.objects.raw("select * from item where title like %s", [query])

Query returning Fatal error: Cannot use object of type QueryResult as array

Hi I am running my own php/mysql application which has its own users table and is imbedded into a joomla site which has its own users table, when i create a new user in my app it creates an associated record in joomla table so i can manage single sign on. This works fine, however I am now trying to delete the user from the joomla table when I delete from my application, this is code:
$rstmp = CustomQuery("select id as id from zzz_users where email='".$deleted_values["Email"]."'");
$datatmp = db_fetch_array($rstmp);
$id = $rstmp["id"];
//Delete from joomla tables
$sql2 = "DELETE * FROM zzz_user_usergroup_map WHERE user_id='$id'"; CustomQuery($sql2);
$sql3 = "DELETE * FROM zzz_users WHERE email='".$deleted_values["Email"]."'"; CustomQuery($sql3);
But it is returning with the following error:
Fatal error: Cannot use object of type QueryResult as array
Help?
Instead of access to id like $id = $rstmp["id"]; you should access to it like $id = $datatmp["id"]; as on the other way you are trying to access to the query result without using fetch

SQL WHERE LIKE clause in JSF managed bean

Hi i have this managed bean where it makes MySQL queries, the problem here is the SQL statement makes a '=' condition instead of 'LIKE'
Here is the code in my managed bean.
Connection con = ds.getConnection();
try{
if (con == null) {
throw new SQLException("Can't get database connection");
}
}
finally {
PreparedStatement ps = con.prepareStatement(
"SELECT * FROM Clients WHERE Machine LIKE '53'");
//get customer data from database
ResultSet result = ps.executeQuery();
con.close();
List list;
list = new ArrayList();
while (result.next()) {
Customer cust = new Customer();
cust.setMachine(result.getLong("Machine"));
cust.setCompany(result.getString("Company"));
cust.setContact(result.getString("Contact"));
cust.setPhone(result.getLong("Phone"));
cust.setEmail(result.getString("Email"));
//store all data into a List
list.add(cust);
}
return list;
Here the SELECT command does not pull all the numbers in 'Machine' column which is like 53, but if i enter a whole value, such as the complete number (53544) in place of 53 then the result is pulled up. I am confused !!
Also if i replace the above select statement with SELECT * FROM Clients the entire database is stored in list. Any ideas ?
Use wildcards:
Like '%53%'
...means everything that contains '53'.
Like '%53' - it ends with 53
LIKE '53%' - it starts with 53
You can also use _ if You want to replace a single character.
You can find a descriptipn HERE
You sql query should be
"SELECT * FROM Clients WHERE Machine LIKE '%53%'

error in mysql query statement in with order by query

i am using jsp page and i can easily done simple select query but as i am new bee i don't know how to write a query ..in which i am on the basis of selected check box i want to show sorted data ...for that i write following code
java.sql.ResultSet rs;
out.println(sort.toString());
StringBuffer myquery=new StringBuffer("select * from message");
if(count != 0)
{
myquery.append(" ORDER BY ");
myquery.append(sort);
}
rs=stmt.executeQuery(myquery.toString());
in above..sort is the String that is contain column field on which i wnat to sort...but it is giving me sql query statment error how can i solve or rewrite statements..