How to insert JSONObject inside MySQL using java? - java

I'm trying to insert a JSONObject that contains a couple of JSONArrays in it inside a MySQL database that I have.
This is what I'm currently trying to do:
JSONObject fiveMin = new JSONObject();
JSONArray data = new JSONArray();
data.add(45);
fiveMin.put("data", data);
String query = "UPDATE frame_data.all_frame_data"
+ "SET 5_min_data = " + fiveMin
+ " WHERE stock_id = 1";
stmt.executeUpdate(query);
However, it's giving me a null pointer exception.
Anyone know how to fix this? I've been stuck on this for days

your Query is not correct you need a space after frame_data.all_frame_data because this now look like frame_data.all_frame_dataSET 5_min_data, change your Query to be like this :
String query = "UPDATE frame_data.all_frame_data SET 5_min_data = " + fiveMin
+ " WHERE stock_id = 1";
Second i don't think that there are a type JSONObject in MySql so i think you are using a varchar or a text to store your data, so fiveMin should convert to a String and not set like you do for example :
fiveMin.toString();
You query should look like this :
String query = "UPDATE frame_data.all_frame_data SET 5_min_data = '" + fiveMin.toString()
+ "' WHERE stock_id = 1";
I suggest to use PreparedStatement you can learn more here : PreparedStatement
Thank you.

Related

use jpa nativequery multiple columns in object list array

Use jpa nativequery multiple columns in object list array
List<Object []> queryList = new ArrayList<>();
String[] arr = {"val1", "val2"};
queryList.add(arr);
String sql = SELECT * FROM TABLE A WHERE (A.COL1, A.COL2) IN (:queryList)
Query query = entityManager.createNativeQuery(sql);
query.setParameter("queryList", queryList);
In postgresql like this
SELECT * FROM TABLE A WHERE (A.COL1, A.COL2) IN (('val1', 'val2'), ('val3', 'val4'));
Here is the Exception
Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: record = bytea
建議:No operator matches the given name and argument types. You might need to add explicit type
Is this possible?
I would try to restructure the query as follows:
SELECT * FROM TABLE A
WHERE (A.COL1 = 'val1' and A.COL2 = 'val2')
OR (A.COL1 = 'val3' and A.COL2 = 'val4')
This would allow the query to be constructed as follows:
List<String[]> queryList = new ArrayList<>();
String[] arr = {"val1", "val2"};
String[] arr = {"val3", "val4"};
queryList.add(arr);
String sql = "SELECT * FROM TABLE A "; //dont forget space at end
if (!queryList.isEmpty()){
sql = sql + "WHERE "; //dont forget space at end
for (String[] queryParam : queryList ){
sql = sql + " (A.COL1 = '"+ queryParam[0] + "' and A.COL2 = '" + queryParam[1] + "') OR "; //dont forget space at end and simple colons for param
}
//finally remove the last OR.
Integer indexLastOR = sql.lastIndexOf("OR");
sql = sql.substring(0, indexLastOR);
}
Query query = entityManager.createNativeQuery(sql);
This will also allow the query to be implemented without being native, which is advisable to maintain the JPA philosophy.

MismatchedTokenException: expecting "set", found '='

In my java spring boot application, i am working with postgresql. I am trying to run the below query
String update = "update User" +
"set temporaryRandomToken = :randomToken" +
"where id = :userId";
org.hibernate.query.Query<?> sql = createHql(update)
.setParameter("randomToken", "12aswqq")
.setParameter("userId", 1);
The problem is, when i run the query it complains with
MismatchedTokenException: expecting "set", found '='
The userId, and the randomToken must change dynamically, so do not offer my a static query string.
You need a space in the beginning of 2 lines (before "set" and "where"):
String update = "update User" +
" set temporaryRandomToken = :randomToken" +
" where id = :userId";
Seems like you forgot to add an extra whitespace between 'User' and 'set'
You're missing a space. Change
String update = "update User" +
to:
String update = "update User " +

Couchbase parameterized N1QL query IN statement

Using com.couchbase.client, java-client version 2.2.7 I have been unable to get a n1ql query working that uses an IN statement with multiple items see my example query and java code below
public int getCountForDuration(Long startTime, Long endTime, String ids){
JsonObject placeHolders = JsonObject.create().put("ids", ids).put("startTime", startTime).put("endTime", endTime);
N1qlQuery query = N1qlQuery.parameterized(COUNT_STATEMENT, placeHolders)
N1qlQueryResult result = bucket.query(query);
...
}
public static final String COUNT_STATEMENT = "select count(*) as count " +
"from bucketName " +
"where docType = 'docId' " +
"and (id IN [$ids]) " + <----- OFFENDING LINE
"and publishTimestamp between $startTime and $endTime";
I've tried setting ids using ('), ("), and (`) such as:
ids = "'123', '456'";
ids = "\"123\" , \"456\";
ids = "`123`,`456`";
None of these are working when there are multiple ids however if there is only one such as ids = "'123'" it works fine. Also my query works if I use it using CBQ on the terminal.
My question is this how do I crate a parameterized N1QL query which
can take multiple items in an IN statement?
Removing the brackets around the $ids in the statement and putting the actual ids into placeholders as a JsonArray object should work:
JsonObject placeHolders = JsonObject.create()
.put("ids", JsonArray.from("id1", "id2", "id3"))
.put("startTime", startTime)
.put("endTime", endTime);

fetch value from SQL query list

So i just wrote down this SQL query and i am trying to capture the value of rest_id in query.list(). However, this is giving the value as [1] . I want just 1 without the braces. How do i do it? Please check the code below for reference:
String sql1 = "select rest_id from rest_details where rest_name = '" + nameclicked + "' and rest_location = '" +locclicked + "'" ;
SQLQuery query1 = session.createSQLQuery(sql1);
System.out.println("sql1 " + query1.list());
Use below code to get the element inside list:
System.out.println("sql1 " + query1.list().get(0));
This always returns only the first element from the list.
Replace
System.out.println("sql1 " + query1.list());
By :
for(String id : query1.list() ) System.out.println("sql1 " + id);

How to write native SQL queries in Hibernate without hardcoding table names and fields?

Sometimes you have to write some of your queries in native SQL rather than hibernate HQL. Is there a nice way to avoid hardcoding table names and fields and get this data from existing mapping?
For example instead of:
String sql = "select user_name from tbl_user where user_id = :id";
something like:
String sql = "select " + Hibernate.getFieldName("user.name") + " from " + Hibernate.getTableName(User.class) + " where " + Hibernate.getFieldName("user.id") + " = :id";
It is possible to get this information as shown below, but I am not sure that I would do this in production code unless I really need the table names to be changeable after the code has been compiled. Otherwise, is it really worth the readability cost to your code to have this?
AbstractEntityPersister metadata =
(AbstractEntityPersister) sessionFactory.getClassMetadata(User.class);
String tableName = metadata.getTableName();
String[] columnNames = metadata.getKeyColumnNames();

Categories

Resources