Android - SQLiteException: near "=": syntax error (code 1) - java

I am trying to log id from users table and jobname from jobs table using user id
String select = "SELECT jobname FROM " + TABLE_JOBS+ "where userid =" +myid;

"SELECT jobname FROM " + TABLE_JOBS+ "where userid =" +myid;
You need whitespace between identifiers such as your table name and keywords such as where:
"SELECT jobname FROM " + TABLE_JOBS+ " where userid =" +myid;

You're missing a whitespace before the where clause, so it gets appended directly to the table name, and you effectively don't have a where clause:
String select = "SELECT jobname FROM " + TABLE_JOBS+ " where userid =" +myid;
// whitespace was missing here -----------------------^

Related

Remove exception No entity found for query

I use this code to make SQL request to find DB record:
public Optional<Subscription> findSubscriptionsByUserEmail(String email) {
String hql = "SELECT s " +
"FROM " + Subscription.class.getName() + " s " +
"INNER JOIN " + Orders.class.getName() + " o ON s.orderId = o.id " +
"INNER JOIN " + Users.class.getName() + " u ON u.id = o.userId " +
"WHERE u.email = :email " +
"ORDER BY s.createdAt DESC ";
TypedQuery<Subscription> query = entityManager.createQuery(hql, Subscription.class).setMaxResults(1).setParameter("email", email);
Optional<Subscription> subscription = Optional.of(query.getSingleResult());
return subscription;
}
But when I don't have a record I get exception: No entity found for query
Do you know how I can skip this exception and continue code execution?
The simplest way to do it is either to try/catch the optional object to see there has been a data sent back or make simple check to see if the optional has an object in it.
Eg:
!subscription.isPresent()? null:subscription;

How to Dynamically Assign Table Name in mysql Server

I am trying To Create Tables in mysql dynamically And Assign them Name Using The Email Address User Provided. But Whenever I try to Assign Table Name dynamically it shows me error and i don,t know anyother way to fulfil my requirement.
Here is The Code I Wrote
String TableName = Email.getText();
try {
String myTableName = "CREATE TABLE '" + TableName + "' "
+ "(id INTEGER not NULL, "
+ " first VARCHAR(255), "
+ " last VARCHAR(255), "
+ " age INTEGER, "
+ " PRIMARY KEY ( id ))";;
Class.forName(m.RegisterationString);
java.sql.Connection con;
con = DriverManager.getConnection(m.URL, m.UserName, m.Password);
Statement State = con.createStatement();
//This line has the issue
State.executeUpdate(myTableName);
System.out.println("Table Created");
}
In MySQL the name of table should not be between '' it can be between :
String myTableName ="CREATE TABLE `" + tableName + "`"
//--------------------------------^-----------------^
Note for good pratice don't start the name of variable with upper letter like State or TableName, Email

Mysql query with In clause regex

I have a SQL query like this:
"select f.filterid as filtename, f.id as filtertext " +
"from filter f " +
"where group_Id = '" + id +"' " +
"OR groupIds like '%." + id + ".%' ";
And I want to pass a list of ids to this query to make performance better. I don't know whether REGEX works with in an IN clause. And I tried the below one which is not working and not sure what to use in case of REGEX.
"select f.filterid as filtename, f.id as filtertext from filter f " +
"where group_Id in ("+StringUtils.join(ids, "','")+")" +
"OR groupIds in ("+StringUtils.join(ids, "','")+")"";
Thanks.
I would recommend to use the Query#setParameter to achieve this, if you are using JPA you can easily supply your ids list in the setParameter.
But for your current resolution you may try the below changes.
Not sure if your group_Id column expects integer or string datatype, well I will propose changes for either of the cases.
If it expects String - You are missing the starting " ' " change your code as below
If it expects integer type - You should not wrap your comma separator with " ' ", remove them as below
"select f.filterid as filtename, f.id as filtertext from filter f " + "where group_Id in ("+StringUtils.join(ids, ",")+")" + "OR groupIds in ("+"'"+StringUtils.join(ids, "','")+"'"+")";
Trying running this query and see if you get the desired resultset
Perhaps the problem lies in the use of method StringUtils.join.
you can edit your sql like the following code.
select f.filterid as filtename, f.id as filtertext from filter f where group_Id in ('groupA_id', 'groupB_id', 'groupC_id')
if your ids is {"groupA_id", "groupB_id", "groupC_id"}, then
"select f.filterid as filtename, f.id as filtertext from filter f where group_Id in (" + "'" + StringUtils.join(ids, "','") + "'" +")"
Try Something like this:
Query query = session.Query("select f.filterid as filtename, f.id as filtertext from filter f where group_Id in :list");
query.SetParameterList(":list", ListOfIds);

Named Query to SELECT rows with MAX(column name), DISTINCT by another column

I have a case similar to the one described in this question, I wrote an identical query which works, but when I try to write it as a jpql named query, I'm getting an error.
My query:
#NamedQuery(
name = "findRankingsBetween",
query = "SELECT rt FROM Rankingtable rt " +
"INNER JOIN " +
"(SELECT teamId, MAX(lastupdate) as MaxDateTime " +
"FROM Rankingtable " +
"GROUP BY teamId) grouped " +
"ON rt.teamId = grouped.teamId " +
"AND rt.lastupdate = grouped.MaxDateTime " +
"WHERE rt.lastupdate BETWEEN :from AND :to"
)
Error:
Error in named query: findRankingsBetween: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 79
How to write the query properly in jpql?
As noted in this answer, a subquery in JPQL can only occur in select and where clauses.
Hibernate doc.
An equivalent query in JPQL is:
"SELECT rt FROM Rankingtable rt " +
"WHERE rt.lastupdate = (SELECT MAX(r2.lastupdate) " +
"FROM Rankingtable r2 " +
"WHERE r2.teamid = rt.teamid) " +
"AND rt.lastupdate BETWEEN :from AND :to"

Copy values from one table to another with 'where' condition

I want to copy values from songDetails table to playlistDetails table.
here is my code :
public void transferData(String name) {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "INSERT INTO "+ TABLE_CURRENTLIST + " SELECT * FROM " + TABLE_DATA + " WHERE " + KEY_ALBUMNAME+ " = " + name + "";
db.execSQL(selectQuery);
}
While executing this code, it throws this exception
01-31 01:29:49.426: E/AndroidRuntime(3102): android.database.sqlite.SQLiteException: no such column: unknown (code 1): , while compiling: INSERT INTO PlayListDetails SELECT * FROM songDetails WHERE albumName = unknown
the value of 'name' variable is correct. And i want to copy only the rows which have the albumName as unknown.
I'm struggled with this. Please help me.
You are missing single quotes around query param value (unknown).
Your query should be
String selectQuery = "INSERT INTO "+ TABLE_CURRENTLIST + " SELECT * FROM " + TABLE_DATA + " WHERE " + KEY_ALBUMNAME+ " = '" + name + "'";
My suggestion would be to use PreparedStatement style parameters.

Categories