How to write SQL query in Java to get data from Snowflake - java

I am trying to write this Snowflake query into Java code:
copy into s3://snowflake171
from USER_TABLE
storage_integration = s3_int
file_format = CSV_TEST;
I am writing it like this:
String q ="COPY INTO s3://snowflake171\n" +
" FROM \"TEST\".\"PUBLIC\".\"USER_TABLE\"WHERE\"ID\\\"=?\"\n" +
" storage_integration = s3_int\n" +
" file_format = CSV_TEST";
But I am getting this error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [COPY INTO s3://snowflake171
FROM "TEST"."PUBLIC"."USER_TABLE"WHERE"ID\"=?"
storage_integration = s3_int
file_format = CSV_TEST]; nested exception is net.snowflake.client.jdbc.SnowflakeSQLException: SQL compilation error:
syntax error line 1 at position 5 unexpected '<EOF>'.
What am I missing?

As the latest error message is "SQL access control error: Insufficient privileges to operate on integration 'S3_INT'", can you try to grant USAGE permission on s3_int to your role? Are you sure you set the correct role when connecting?
String url = "jdbc:snowflake://<account_identifier>.snowflakecomputing.com";
Properties prop = new Properties();
prop.put("user", "<user>");
prop.put("privateKey", PrivateKeyReader.get(PRIVATE_KEY_FILE));
prop.put("db", "<database_name>");
prop.put("schema", "<schema_name>");
prop.put("warehouse", "<warehouse_name>");
prop.put("role", "<role_name>");

Related

how we can fix "java.sql.SQLSyntaxErrorException: [duplicate]

This question already has answers here:
SQL query: Can't order by column called "order"?
(7 answers)
Closed 3 years ago.
i want to show the list of orders through api but we have an error in the DAO SQLSyntaxErrorException.
#RequestMapping("list")
public String getAllOrders() {
//APIResponse response=new APIResponse();
List<OrderBeans> orderList = orderDao.selectAll();
return new Gson().toJson(orderList);
}
public List<OrderBeans> selectAll() {
System.out.println("DAO => " + jdbcTemplate);
List<OrderBeans> orders = null;
String query = "select * from " + TABLE_ORDER +"";
try {
orders = jdbcTemplate.query(query, new OrderRowMapper());
} catch (EmptyResultDataAccessException | IncorrectResultSetColumnCountException e) {
}
return orders;
}
3-May-2019 15:01:15.997 SEVERE [http-nio-8084-exec-109] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcher] in context with path [/Grocery] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [select * from order]; 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 'order' at line 1] with root cause
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 'order' at line 1
I am speculating here that your error is due to your SQL table being called ORDER, which of course is a reserved keyword in almost all versions of SQL. You should always avoid naming your tables and columns with reserved keywords. As a workaround, you could build your query as follows, placing backticks around the table name:
String query = "select * from `" + TABLE_ORDER + "`";
However, the above should only be viewed as a temporary solution until you get a chance to fix your data model.

SQL Error saying that I have not specified a 3rd Parameter

I am developing a Java Restful Web Application. When I try to execute this SQL Query using JDBCTemplate it gives and error saying that,
SEVERE: Servlet.service() for servlet [spring-mvc] in context with path [/paf_project] threw exception [Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [select count(*) from customer where email = ? AND password = ? AND status = ?]; nested exception is java.sql.SQLException: No value specified for parameter 3] with root cause
java.sql.SQLException: No value specified for parameter 3
Here is my Function which I am going to get the row count of my table.
public int userLogin(String un, String pw) {
String status = "active";
String sql = "select count(*) from customer where email = ? AND password = ? AND status = ?";
int count = template.queryForObject(sql, new Object[] {un, pw, status}, Integer.class);
if(count >= 1) {
return 1;
}

Postgresql JPA Hibernate create Database

I'm having trouble with Postgresql with JPA Hibernate.
My code :
#Transactional
public void createDatabase(User user) {
Query q = em.createNativeQuery("CREATE USER \"" + user.getEmail()
+ "\" WITH PASSWORD '" + user.getPasswordHash() + "' ;");
q.executeUpdate();
Query q1 = em.createNativeQuery("CREATE DATABASE " + user.getDb() + ";");
q1.executeUpdate();
Query q2 = em.createNativeQuery("GRANT ALL PRIVILEGES ON " + user.getDb()
+ " TO '" + user.getEmail() + "';");
q2.executeUpdate();
}
I'm having the following Error.
Hibernate: CREATE USER "test" WITH PASSWORD 'test' ;
Hibernate: CREATE DATABASE test;
2015-05-08 15:15:49.531 WARN 1952 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 25001
2015-05-08 15:15:49.531 ERROR 1952 --- [nio-8080-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : ERREUR: CREATE DATABASE cannot be created in a transaction bloc
2015-05-08 15:15:49.545 ERROR 1952 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
org.postgresql.util.PSQLException: ERREUR: CREATE DATABASE cannot be created in a transaction bloc
If i delete the Transaction Annotation i get the following error :
javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:71)
at com.esisa.pfe.business.DefaultUserService.createDatabase(DefaultUserService.java:56)
at com.esisa.pfe.controllers.ClientController.addAbonnement(ClientController.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
The JPA EntityManager is not the object to create new databases or users. see documentation what for entity manager is used. If you want to create a new database from java you can do this with simple JDBC - here some example code:
// without db name
public static final String HOST = "jdbc:postgresql://localhost:5432/";
Statement stmt = conn.createStatement();
stmt.executeUpdate("CREATE DATABASE JavaDB");
stmt.executeUpdate("CREATE USER java_user WITH PASSWORD \'java\'");
// ...
JPA 2.1 allows you to create the datastore tables etc (and optionally schema too depending on JPA implementation and datastore) when creating the EntityManagerFactory.

Getting org.hibernate.hql.ast.QuerySyntaxException though it works fine sql server?

i have below code snippet. It throws the exception at line 3 but query works fine managemnt studio(sql server 2005)
String query = "select * from user where userId=" + profileId
+ " and spaceName='" + spaceName + "'";
Session session = HibernateUtil.getSession();
List<PersonDetailsData> personDetailsData = new ArrayList<PersonDetailsData>(
session.createQuery(query).list()); //line 3
Here is the exception
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: * near
line 1, column 8 [select * from user where userId=216 and
spaceName='DIG']
I am not able to figure out what's the problem with query when it is running fine in management sudio?
It's native query, not hql.
If you have mapped table field to class fields you need
session.createSQLQuery(query, PersonDetailsData.class).list();
or create hql type query -
select p from PersonDetailData p where p.userId = :userId and p.spaceName =:spaceName
and use parameters in query, not direct values.
As you are using sql query so you have to create a sql query such as
sess.createSQLQuery("SELECT * FROM CATS").list();
see the source source

nested exception is java.sql.SQLException: Invalid column name ORACLE

I tried to execute the following oracle query using JdbcTemplate in Java:
select RESOURCE_ID
from REPRO_PRINTING_JOB
where (USER_ID=? and PRINTING_CENTER_ID=?)
group by RESOURCE_ID
union all
select RESOURCE_ID
from REPRO_PRINTING_JOB_OLD
where (USER_ID=? and PRINTING_CENTER_ID=? and STATE='CM')
group by RESOURCE_ID
The query is working perfectly in oracle query browser but its not working during the execution in java. What could be the source of this problem? I´ve heard something about Jdbc cannot handle case sensitive. Is this true?
ADDED JAVA CODE(CORRECTED) :
I call the query using getStatement() which retrieves the query from external source(a properties file) as belows :
public List<PrintingJob> getPrintingJobsByCreatedUserId(String createdUserId, String userId) {
if(log.isDebugEnabled()) {
log.debug("getReportItemsByUserId(" + createdUserId + "," + userId + ")");
}
try {
System.out.println("getPrintingJobsByResourceId : createdUserId :"+createdUserId+",userId : "+userId);
return getJdbcTemplate().query(getStatement("gen.report.userid"),
new Object[]{createdUserId, userId, createdUserId, userId},
new PrintingJobMapper());
} catch (DataAccessException ex) {
log.error("Error executing query: " + ex.getClass() + ":" + ex.getMessage());
return null;
}
}
The reason you are getting this error is because it is an error from the JDBC driver or java.sql API, not from the database. Note the lack of ORA-XXXXX in the exception message. If it contained that, then it would be related to syntax, invalid name or something that would go wrong on the database server side.
SQLExceptions are thrown in java for anything related to the SQL api, not just from errors that occur when statements are sent over the connection... In this case, it is likely that the query in fact ran correctly but the result set API is giving you errors (rs.getLong("blah"), where column "blah" doesn't exist in your select) is causing problems.

Categories

Resources