How to solve this sql string in Dbutils ? - java

public List<Hero> list() throws SQLException {
return list(0, Short.MAX_VALUE);
}
public List<Hero> list(int start, int count) throws SQLException{
Connection c = this.getConnection();
QueryRunner runner = new QueryRunner();
String sql = "select * from hero order by id desc limit ?,? ";
Object params[] = {"start", "count" };
List<Hero> heros = (List<Hero>) runner.query(c,sql,new BeanListHandler(Hero.class),params);
DbUtils.closeQuietly(c);
return heros;
}
Before that I have imported Dbutils JAR that I need, like org.apache.commons.dbutils.handlers.BeanListHandler and
org.apache.commons.dbutils.QueryRunner
But after running my project, it goes wrongs whose message is :
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 ''start','count'' at line 1 Query: select * from hero order by id
desc limit ?,? Parameters: [start, count]
I know that something wrong in program, but I dont want to find all, I just want to find part of my table using limit ?.? (I only know this sql sentence can do that).
Could u please help me?

You're passing strings as your parameters, so it's running your SQL limit literally as LIMIT 'start','count'
Try this instead:
Object params[] = {start, count };
So that you're building a parameter array of your actual int values (now autoboxed to Integer)

Related

Postgres Query returning empty result set from Java

String query = "SELECT distinct on (l->>'test_id') l->>'test_id' test_id,
l->>'result' result,l->>'indication' indication
FROM Ltable,
jsonb_array_elements(lines) with ordinality a(l) WHERE pat_id = ?
AND result_received <= ? AND (l->>'test_id' = ? OR l->>'test_id' = ? )
and archived = false ORDER BY l->>'test_id', result_received DESC LIMIT 2";
jdbcTemplate.query(query, rs -> {
while(rs.next()){
}
}val1, val2, val3, val4);
The above query when executed from pgAdmin returns some rows but when executed from a java app returns an empty resultSet, the line while(rs.next()) never gets entered.
I have logged the query parameters to make sure the correct data is being passed into the query.
Please help look at at and let me know if there's a mistake I'm making somewhere.

My SQL prepared statement to get sum of points by certain id?

I am trying to get total number of points back from my MySQL database using JDBC and prepared statements. I currently have
private static final String SELECT_TOTAL_POINTS_FROM_LEVEL_BY_CUSTOMER =
"select sum(points) from level_up where customer_id = ?";
#Override
public int getTotalLevelUpPointsByCustomerId(int customerId) {
int points = jdbcTemplate.queryForObject(SELECT_TOTAL_POINTS_FROM_LEVEL_BY_CUSTOMER,
Integer.class);
return points;
}
and my controller method is
#GetMapping("/points/{customerid}")
ResponseStatus(HttpStatus.OK)
public int getTotalPoints(#PathVariable("customerid") int customerId) {
return service.getTotalPoints(customerId);
}
How can i just get the points back from the database with just the customer id?
ERROR BELOW
"message": "StatementCallback; bad SQL grammar [select sum(points) from level_up where customer_id = ?]; nested exception is java.sql.SQLSyntaxErrorException: 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",
You were using a method that doesn’t allow for passing arguments. Use a method that allows for passing in arguments, like: https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html#queryForObject-java.lang.String-java.lang.Object:A-int:A-java.lang.Class-

How do you access the value of a DQL count() query in Java Program

I want to get to the value I am finding using the COUNT command of DQL.Normally I enter the column name I want to access into the getInt() getString() method. What I'm supposed to do when there is no specific colomn name.
{
String query = "select count(*) as count from dm_user;";
return query;
}
Code to fetch the result
{
IDfCollection total = dql.execute(session, IDfQuery.DF_READ_QUERY);
while (total.next()){
cint = total.getInt("count");
}
Tomcat Result
DfException:: THREAD: http-8080-2; MSG: [DM_QUERY_E_SYNTAX]error: "A Parser Error (syntax error) has occurred in the vicinity of: select count(*) as count"; ERRORCODE: 100; NEXT: null
You are using count which is a keyword for your column custom name, the error you posted clearly says it: A Parser Error (syntax error)
This will do
select count(*) as quantity from dm_user;
and fetching result like
IDfCollection total = dql.execute(session, IDfQuery.DF_READ_QUERY);
while (total.next()){
cint = total.getInt("quantity");
will work
While #Miki answered it already but I like to add one small thing here that below code should work too if you haven't specified any alias.
{
IDfCollection total = dql.execute(session, IDfQuery.DF_READ_QUERY);
while (total.next()){
cint = total.getInt("count(*)");
}
}

Execute "sp_msforeachdb" in a Java application

Hi StackOverflow community :)
I come to you to share one of my problems...
I have to extract a list of every table in each database of a SQL Server instance, I found this query :
EXEC sp_msforeachdb 'Use ?; SELECT DB_NAME() AS DB, * FROM sys.tables'
It works perfectly on Microsoft SQL Server Management Studio but when I try to execute it in my Java program (that includes JDBC drivers for SQL Server) it says that it doesn't return any result.
My Java code is the following :
this.statement = this.connect.createStatement(); // Create the statement
this.resultats = this.statement.executeQuery("EXEC sp_msforeachdb 'Use ?; SELECT DB_NAME() AS DB, * FROM sys.tables'"); // Execute the query and store results in a ResultSet
this.sortie.ecrireResultats(this.statement.getResultSet()); // Write the ResultSet to a file
Thanks to anybody who will try to help me,
Have a nice day :)
EDIT 1 :
I'm not sure that the JDBC driver for SQL Server supports my query so I'll try to get to my goal in another way.
What I'm trying to get is a list of all the tables for each database on a SQL Server instance, the output format will be the following :
+-----------+--------+
| Databases | Tables |
+-----------+--------+
So now I'm asking can someone help me to get to that solution using SQL queries thru Java's JDBC for SQL Server driver.
I also wish to thanks the very quick answers I got from Tim Lehner and Mark Rotteveel.
If a statement can return no or multiple results, you should not use executeQuery, but execute() instead, this method returns a boolean indicating the type of the first result:
true: result is a ResultSet
false : result is an update count
If the result is true, then you use getResultSet() to retrieve the ResultSet, otherwise getUpdateCount() to retrieve the update count. If the update count is -1 it means there are no more results. Note that the update count will also be -1 when the current result is a ResultSet. It is also good to know that getResultSet() should return null if there are no more results or if the result is an update count.
Now if you want to retrieve more results, you call getMoreResults() (or its brother accepting an int parameter). The return value of boolean has the same meaning as that of execute(), so false does not mean there are no more results!
There are only no more results if the getMoreResults() returns false and getUpdateCount() returns -1 (as also documented in the Javadoc)
Essentially this means that if you want to correctly process all results you need to do something like below:
boolean result = stmt.execute(...);
while(true)
if (result) {
ResultSet rs = stmt.getResultSet();
// Do something with resultset ...
} else {
int updateCount = stmt.getUpdateCount();
if (updateCount == -1) {
// no more results
break;
}
// Do something with update count ...
}
result = stmt.getMoreResults();
}
NOTE: Part of this answer is based on my answer to Java SQL: Statement.hasResultSet()?
If you're not getting an error, one issue might be that sp_msforeachdb will return a separate result set for each database rather than one set with all records. That being the case, you might try a bit of dynamic SQL to union-up all of your rows:
-- Use sys.tables
declare #sql nvarchar(max)
select #sql = coalesce(#sql + ' union all ', '') + 'select ''' + quotename(name) + ''' as database_name, * from ' + quotename(name) + '.sys.tables'
from sys.databases
select #sql = #sql + ' order by database_name, name'
exec sp_executesql #sql
I still sometimes use INFORMATION_SCHEMA views as well, since it's easier to see the schema name, among other things:
-- Use INFORMATION_SCHEMA.TABLES to easily get schema name
declare #sql nvarchar(max)
select #sql = coalesce(#sql + ' union all ', '') + 'select * from ' + quotename(name) + '.INFORMATION_SCHEMA.TABLES where TABLE_TYPE = ''BASE TABLE'''
from sys.databases
select #sql = #sql + ' order by TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME'
exec sp_executesql #sql
Be aware that this method of string concatenation (select #sql = foo from bar) may not work as you intend through a linked server (it will only grab the last record). Just a small caveat.
UPDATE
I've found the solution !
After reading an article about sp_spaceused being used with Java, I figured out that I was in the same case.
My final code is the following :
this.instances = instances;
for(int i = 0 ; i < this.instances.size() ; i++)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
this.connect = DriverManager.getConnection("jdbc:sqlserver://" + this.instances.get(i), "tluser", "result");
this.statement = this.connect.prepareCall("{call sp_msforeachdb(?)}");
this.statement.setString(1, "Use ?; SELECT DB_NAME() AS DB, name FROM sys.tables WHERE DB_NAME() NOT IN('master', 'model', 'msdb', 'tempdb')");
this.resultats = this.statement.execute();
while(true)
{
int rowCount = this.statement.getUpdateCount();
if(rowCount > 0)
{
this.statement.getMoreResults();
continue;
}
if(rowCount == 0)
{
this.statement.getMoreResults();
continue;
}
ResultSet rs = this.statement.getResultSet();
if(rs != null)
{
while (rs.next())
{
this.sortie.ecrireResultats(rs); // Write the results to a file
}
rs.close();
this.statement.getMoreResults();
continue;
}
break;
}
this.statement.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
It tried it out and my file has everything I want in it.
Thank you all for your help ! :)

hibernate java select queries

i am new to this and today i tried to play hibernate with a method that returns the result of selected row...if is selected then it can return the result in int.. here is my method
public int validateSub(String slave, String source, String table){
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Query q = session.createQuery("from Subscribers where slave = :slave AND source = :source AND tbl = :tbl");
q.setParameter("slave", slave);
q.setParameter("source", source);
q.setParameter("tbl", table);
int result = q.executeUpdate();
return result;
}
from this method i tried to validate the 3 values that i get from the Subscribers table but at the end i tried to compile having this error
Exception in thread "Thread-0" org.hibernate.hql.QueryExecutionRequestException: Not supported for select queries [from com.datadistributor.main.Subscribers where slave = :slave AND source = :source AND tbl = :tbl]
You can have a look at the below links that how executeUpdate works, one is from the hibernate docs and other the java docs for JPA which defines when the exception is thrown by the method
http://docs.oracle.com/javaee/6/api/javax/persistence/Query.html#executeUpdate()
https://docs.jboss.org/hibernate/orm/3.2/api/org/hibernate/Query.html#executeUpdate()
Alternatively you can use
List list = query.list();
int count = list != null ? list.size() : 0;
return count;
you are running a select query, Eventhough you are not using the select keyword here hibernate will add that as part of the generated SQL.
what you need to do to avoid the exception is the say
q.list();
now, this will return a List (here is the documentation).
if you are trying to get the size of the elements you can say
Query q = session.createQuery("select count(s) from Subscribers s where slave = :slave AND source = :source AND tbl = :tbl");
Long countOfRecords = (Long)q.list().get(0);
you can execute update statements as well in HQL, it follows a similar structure as SQL (except with object and properties).
Hope this helps.
here you want to select record so it is posible without select key word
sessionFactory sesionfatory;
ArrayList list = (ArrayList)sessionfactory.getCurruntSession().find(from table where name LIKE "xyz");
long size = list.get(0);
I also happened to make the same mistake today.
Your SQL statement is not correct.
You can try:
DELETE from Subscribers WHERE slave = :slave AND source
Try this:
int result = q.list().size();

Categories