Simple difficulty with HQL Query - mysql

I am having a trouble with executing an HQL query like this:
select new myPackage.view.CoverDocumentReportView(Re.code AS fulCd,
Re.creditPrice AS crtprc,
Re.debitPrice AS dbtprc,
(Re.debitPrice - Re.debitPrice) AS redbtprc,
(Re.creditPrice- Re.creditPrice) AS recrtprc,
(Re.debitPrice-Re.creditPrice) AS rem)
from
(select fullCode as code,
sum(creditPrice) as creditPrice ,
sum(debitPrice) as debitPrice
from DocumentMaster DM,
DocumentAccount DA,
Tree T ,
AccountTree AT,
DocumentDetailed DD
where DM.id = DA.documentMaster and
DA.accountTree = T.id and
DA.accountTree = AT.id and
DD.documentAccount = DA.id
group by DA.accountTree ) As Re
1)
If I execute this like:
SQLQuery crit = (SQLQuery) session
.createSQLQuery(sql).setResultTransformer(Transformers.aliasToBean(CoverDocumentReportView.class));
ArrayList<CoverDocumentReportView> li = (ArrayList<CoverDocumentReportView>) crit.list();
ERROR 2012-12-22 14:16:19,838 [http-8080-1] org.hibernate.util.JDBCExceptionReporter : 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 '.datx.web.accounting.view.CoverDocumentReportView(Re.code AS fulCd,
Re.creditP' at line 1
2)
If I execute it with this:
Query query = session.createQuery(sql).setResultTransformer(Transformers.aliasToBean(CoverDocumentReportView.class));
ArrayList<CoverDocumentReportView> li = (ArrayList<CoverDocumentReportView>)query.list();
The error will be:
ERROR 2012-12-22 14:51:46,709 [http-8080-1] org.hibernate.hql.ast.ErrorCounter : line 1:224: unexpected token: (
ERROR 2012-12-22 14:51:46,709 [http-8080-1] org.hibernate.hql.ast.ErrorCounter : line 1:308: unexpected token: sum
What is the problem?

SQL and HQL are two different languages.
HQL doesn't support subqueries in from clauses, so this query can't be an HQL query.
And SQL doesn't know about Java objects, and doesn't have any new() function allowing to create them, so the query is not a valid SQL query either.
Make it a valid SQL query, execute it using createSQLQuery(), then iterate through the results and create instances of your objects from the returned rows. Or use a result transformer as you're doing, which will do that for you. the result transformer will use the aliases you assigned to the returned columns of the SQL query to create beans for you. You don't need any new CoverDocumentReportView() in the query to make that work. Read the javadoc for details.

Related

MySQL Syntax with FROM with a var

I got some problems with my MySQL Syntax.
This is my code:
Config.SocietyMoneyTable = 'addon_account_data'
local result = MySQL.Sync.fetchAll("SELECT money FROM #account_table WHERE account_name = #society", {
['#account_table'] = Config.SocietyMoneyTable,
['#society'] = society
})
Error:
[ERROR] [MySQL] [maze_management] An error happens on MySQL for query "SELECT money FROM
'addon_account_data' WHERE account_name = 'society_police'": ER_PARSE_ERROR: You have an
error in your SQL syntax; check the manual that corresponds to your MariaDB server version
for the right syntax to use near ''addon_account_data' WHERE account_name = 'society_police''
at line 1
The Syntax does work when I change the #account_table to the string which is in Config.SocietyMoneyTable. But I need this configed so this is no solution for me.
A query parameter annotated with the # sigil can only be used in place of a scalar value, not a table name or other identifier. You need to use string formatting to get your configurable table name into the query, not a query parameter.
Something like the following:
Config.SocietyMoneyTable = 'addon_account_data'
local queryString = string.format("SELECT money FROM `%s` WHERE account_name = #society",
Config.SocietyMoneyTable)
local result = MySQL.Sync.fetchAll(queryString, {
['#society'] = society
})
I have not tested this code, and I don't use Lua often, so if there are mistakes I will have to leave it to you to resolve them. But it should at least show the principle: identifiers (like table names) must be fixed in the query string, not added as query parameters.

I cannot make binding work with Diesel on MariaDB

I simply wanted to pass an argument to my sql query.
let query = sql("SELECT resa_comment FROM reservation WHERE resa_id = ? ");
let query2 = query.bind::<Integer, _>(1286);
let result : Result<std::vec::Vec<String>, _> = query2.load(&connection);
dbg!(result);
But the result is
[src/bin/show_posts.rs:36] result = Err(
DatabaseError(
__Unknown,
"You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near \'?\' at line 1"
)
)
The SQL query is correct because when I replace the "?" with a constant and remove the "bind", I get a correct result.
I know that I can map the table to a Rust structure but my goal is to pass complex requests with arguments so I was testing Rust and Diesel.
Is there something I missed ? Thanks.
The bind method does not replace question mark, it appends the value to the end of the query. So it should look like this:
let query = sql("SELECT resa_comment FROM reservation WHERE resa_id = ");
// ...
If you need to put value in the middle of the query, then you need to chain bind and sql calls, such as:
sql("SELECT resa_comment FROM reservation WHERE resa_id = ")
.bind::<Integer, _>(1286)
.sql(" AND something > ")
.bind::<Integer, _>(1);
But note that you should avoid writing raw sql if it is not necessary.

MySQL syntax error when executing SQL query

When I try to run the code below I am getting:
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 '?' at line 1`
String query="Select * from DB.Admin where username = ?";
PreparedStatement st=connection.prepareStatement(query);
st.setString(1,request.getParameter("loginid"));
ResultSet rst= st.executeQuery(query);
int count=0;
while(rst.next()){
count++;
}
Please help me in this.
You will have to remove the query argument from your executeQuery call. If you provide the parameter, the query will be executed without binding any values (see Statement for details) - this is why the syntax (i.e. the ?) is invalid.
Execute the query like this:
ResultSet rst = st.executeQuery();
As a side note: you should always wrap Connection, PreparedStatement and ResultSet with a try-with-resources block, e.g.
try (ResultSet rst = st.executeQuery()) {
// read the results
}
This way you can be sure the ResultSet will be closed no matter what happens.

Quering with Python Connector with variables

i am new in python and i have a simple issue that i cannot resolve.
I am in windows platform and unfortunately i cannot change this cause of work. I have to connect to many mysql tables and do sort of things with the extracted data. The code that i have:
conn = mysql.connector.Connect(host='<ip>',user='<user>',\
password='',database='<my database>')
c = conn.cursor()
c.execute ("select field from TABLE")
results = c.fetchall()
for row in results:
c.execute("select * from otherTable where nodo = %s",(str(row[0])))
if c.rowcount == 0:
doSomething()
else:
doOtherThing()
c.close()
when I run this with Python34 i got the error:
"you have an error in your sql synthax; check the manual that corresponds to your mysql server version for the right synthax to use near '%s' at line 1
thanks
you need to put single quotes around your %s like this: c.execute("select * from otherTable where nodo = '%s'",(str(row[0])))
you should also consider putting your query in a variable and then executing it like so:
query = ("select * from otherTable where nodo = '%s'",(str(row[0])))
c.execute(query)
This way helps prevents potential sql injection attacks and allows you to do a print(query) so you can debug the sql statement if you are getting errors.

MySQL Zend Framework - SQLSTATE[42000]: Syntax error or access violation: 1064

I've read every response I could fine on SO before posting this question. Although similar, none addressed my particular problem (or I didn't recognize them doing so).
I have a table class that extends Zend_Db_Table_Abstract. In the model, I'm trying to return a single row using a join() method and based on the table ID like this:
$getCategoryResults = $this->select();
$getCategoryResults->setIntegrityCheck(false)
->from(array('c'=> 'categories', '*'))
->join(array('e' => 'events'),'c.events_idEvent = e.idEvent', array())
->where("e.idEvent = ?", $idEvent);
when I echo the sql object, I get this:
SELECT `c`.* FROM `categories` AS `c`
INNER JOIN `events` AS `e` ON c.events_idEvent = e.idEvent
WHERE (e.idEvent = '1')
Oddly enough, if I use this format,
->where("e.idEvent = $idEvent");
my output is "WHERE (e.idEvent = 1)". The value is not enclosed in ticks, but either seems to work for MySQL. When I run the query in phpMyAdmin, I get this:
idCategory type displayOrder description localStartTime events_idEvent
1 individual 1 5k Run / Walk 2010-02-18 23:59:59 12 team 2 5k Team Category 2010-02-18 23:59:591 1
which is what I expected to see. But when I run my app in a browser, I get this ugliness:
SQLSTATE[42000]: Syntax error or access violation: 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 'SELECT c.* FROM categories AS c INNER JOIN events AS e ON c.events_id' at line 1
I've checked every resource that I can think of. Hopefully, the combined awesomeness of SO uber-experts will make this my last stop. :D
Check out the second part of the error statement. Most likely it is regarding an access violation if the mysql elsewhere.
For reasons unknown to me, the app believed my $pageResult variable wasn't set. I discovered this after adding an isset() to the code like this:
try {
$getCategoryResults = $this->select();
$getCategoryResults->setIntegrityCheck(false)
->from(array('c'=> 'categories', '*'))
->join(array('e' => 'events'),'c.events_idEvent = e.idEvent', array())
->where("e.idEvent = ?", $idEvent);
if (isset($pageResult)) {
$pageResult .= $getCategoryResults;
}
else {
$pageResult = $getCategoryResults;
}
} catch (Exception $e) {
echo ( "Could not find matching categories for event id = $idEvent");
}
Problem went away which, of course, revealed the next problem lurking behind it. :D