The 'length' operator is not allowed to take a parameter as an operand - derby

Our team recently developed a web project with derby database,then found some errors: The 'length' operator is not allowed to take a ? parameter as an operand.
This is my code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class test {
public static void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();//加载驱动
Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/mydb","user","123456");
String sql = "select * from TB_SYS_MODULE where length(?) > 5";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "fudengok");
ResultSet rs = ps.executeQuery();
while(rs.next()) {
System.out.println("MODULE_ID:"+rs.getString(1)+"-----MODULE_NAME:"+rs.getString(2));
}
} catch(Exception e){
e.printStackTrace();
}
}
}
I have searched official document,LENGTH() function allow a dynamic parameter enter link description here. So asking for help!

I'm not sure I understand. Is "fudengok" the name of a column in the TB_SYS_MODULE table?
If so, why not just use:
select * from TB_SYS_MODULE where length(fudengok) > 5

Related

Call BigQuery stored procedure(Routine) using spring boot

I'm trying to call a Google BigQuery stored procedure (Routine) using Spring boot. I tried all the methods of the routines to extract data. However, it didn't help.
Has anyone ever created and called a BigQuery stored procedure (Routine) through the Spring boot? If so, how?
public static Boolean executeInsertQuery(String query, TableId tableId, String jobName) {
log.info("Starting {} truncate query", jobName);
BigQuery bigquery = GCPConfig.getBigQuery(); // bqClient
// query configuration
QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(query)
.setUseLegacySql(false)
.setAllowLargeResults(true)
.setDestinationTable(tableId) .setWriteDisposition(JobInfo.WriteDisposition.WRITE_TRUNCATE).build();
try {
// build the query job.
QueryJob queryJob = new QueryJob.Builder(queryConfig).bigQuery(bigquery).jobName(jobName).build();
QueryJob.Result result = queryJob.execute();
} catch (JobException e) {
log.error("{} unsuccessful. job id: {}, job name: {}. exception: {}", jobName, e.getJobId(),
e.getJobName(), e.toString());
return false;
}
}
package ops.google.com;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryError;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.EncryptionConfiguration;
import com.google.cloud.bigquery.InsertAllRequest;
import com.google.cloud.bigquery.InsertAllResponse;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.bigquery.TableResult;
import com.google.common.collect.ImmutableList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class SelectFromBigQueryFunction {
private static final Logger logger = LogManager.getLogger(SelectFromBigQueryFunction.class);
public boolean tableSelectFromJoin(String key_path) {
String projectID = "ProjectID";
String datasetName = "DataSetName";
String tableName1 = "sample_attribute_type";
String tableName2 = "sample_attribute_value";
boolean status = false;
try {
//Call BQ Function/Routines, functinon name->bq_function_name
//String query = String.format("SELECT DataSetName.bq_function_name(1, 1)");
//Call BQ Stored Procedure, procedure name-> bq_stored_procedure_name
String query = String.format("CALL DataSetName.bq_stored_procedure_name()");
File credentialsPath = new File(key_path);
FileInputStream serviceAccountStream = new FileInputStream(credentialsPath);
GoogleCredentials credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
// Initialize client that will be used to send requests. This client only needs to be created
BigQuery bigquery = BigQueryOptions.newBuilder()
.setProjectId(projectID)
.setCredentials(credentials)
.build().getService();
QueryJobConfiguration queryConfig = QueryJobConfiguration.newBuilder(query).build();
TableResult results = bigquery.query(queryConfig);
results.iterateAll().forEach(row -> row.forEach(val -> System.out.printf("%s,", val.toString())));
logger.info("Query performed successfully with encryption key.");
status = true;
} catch (BigQueryException | InterruptedException e) {
logger.error("Query not performed \n" + e.toString());
}catch(Exception e){
logger.error("Some Exception \n" + e.toString());
}return status;
}
}

Does any embedded DB support JSON datatype?

I'm developing a Spring based web application with postgresql as database. I'm using JSON Datatype in postgresql. I have configured the entity with hibernate custom user type to support JSON Datatype.
Now i want to test my DAO objects using any embedded DB. Is there any embedded DB that support JSON data type which can be used in spring application.
When you use database specific features - like JSON support in PostgreSQL, for safety you have to use the same type of database for testing. In your case you want to test your DAO objects:
assume that PostgreSQL is installed on localhost and make sure that it is the case for all environments where tests run
or even better - try using otj-pg-embedded which downloads and starts PostgreSQL for JUnit tests (I haven't used it in real life projects)
Update
If you are able to run Docker in your test environment instead of embedded databases use real Postgres via TestContainers
package miniCodePrjPkg;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
//import com.wix.mysql.EmbeddedMysql;
//
//import static com.wix.mysql.EmbeddedMysql.anEmbeddedMysql;
//import static com.wix.mysql.ScriptResolver.classPathScript;
//import static com.wix.mysql.distribution.Version.v5_7_latest;
public class DslQueryCollList {
public static void main(String[] args) throws Exception {
// apache comm coll cant ,only array is ok..cant json_object eff
// Map m=Maps.
Map myMap = Maps.newHashMap(ImmutableMap.of("name", 999999999, "age", 22));
Map myMap2 = Maps.newHashMap(ImmutableMap.of("name", 8888888, "age", 33));
List li = new ImmutableList.Builder().add(myMap).add(myMap2).build();
System.out.println(li);
// /db/xx.sql
// EmbeddedMysql mysqld = anEmbeddedMysql(v5_7_latest)
// .addSchema("aschema", classPathScript("iniListCache.sql"))
// .start();
// this just start..and u need a cliednt as common to conn..looks trouble than
// sqlite
String sql = " json_extract(jsonfld,'$.age')>30";
List<Map<String, Object>> query = queryList(sql, li);
System.out.println(query);
// run.query(conn, sql, rsh)
}
private static List<Map<String, Object>> queryList(String sql_query, List li)
throws ClassNotFoundException, SQLException, JsonProcessingException {
sql_query="SELECT * FROM sys_data where "+sql_query;
String sql = null;
Class.forName("org.sqlite.JDBC");
Connection c = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stmt = c.createStatement();
String sql2 = "drop TABLE sys_data ";
exeUpdateSafe(stmt, sql2);
sql2 = "CREATE TABLE sys_data (jsonfld json )";
exeUpdateSafe(stmt, sql2);
// insert into facts values(json_object("mascot", "Our mascot is a dolphin name
// sakila"));
//
for (Object object : li) {
String jsonstr = new ObjectMapper().writeValueAsString(object);
sql = "insert into sys_data values('" + jsonstr + "');";
// sql = "insert into sys_data values('{\"id\":\"19\", \"name\":\"Lida\"}');";
exeUpdateSafe(stmt, sql);
}
//sql = "SELECT json_extract(jsonfld,'$.name') as name1 FROM sys_data limit 1;";
// System.out.println(sql);
QueryRunner run = new QueryRunner();
// maphandler scare_handler
System.out.println(sql_query);
List<Map<String, Object>> query = run.query(c, sql_query, new MapListHandler());
System.out.println(query);
List li9=Lists.newArrayList();
for (Map<String, Object> map : query) {
li9.add(map.get("jsonfld"));
}
return li9;
}
private static void exeUpdateSafe(Statement stmt, String sql2) throws SQLException {
try {
System.out.println(sql2);
System.out.println(stmt.executeUpdate(sql2));
} catch (Exception e) {
e.printStackTrace();
}
}
}

ERROR - oracle.jdbc.pool.OracleDataSource

I'm trying to develop an adf mobile app using jDeveloper and oracle sql developer.
I have connected jDev and sql. I want to populate selectOneChoice comp. that I m gonna fetch datas.
this is my connection method;
package salesorder.application;
import groovy.sql.Sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import oracle.adf.share.jndi.InitialContextFactoryImpl;
import oracle.adfmf.framework.api.AdfmfJavaUtilities;
import oracle.jbo.server.InitialContextImpl;
import oracle.jdbc.connector.OracleConnectionManager;
import oracle.jdbc.pool.OracleDataSource;
public class DBConnection {
public DBConnection() {
super();
}
private static String jdbcUrl = "jdbc:oracle:thin:#10.172.105.37:1521:VIS";
private static String userid = "***";
private static String password = "***";
protected static Connection conn = null;
public static Connection getConnection()throws Exception{
if (conn == null) {
try {
OracleDataSource ds; ds = new OracleDataSource();
ds.setURL(jdbcUrl);
conn=ds.getConnection(userid,password);
} catch (SQLException e) {
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
}
return conn;
}
}
and this, my method to fetch data;
private void Execute() {
Trace.log(Utility.ApplicationLogger, Level.INFO, Customers.class, "Execute",
"!!!!!!!!!!!!!!!!!In COUNTRY Execute!!!!!!!!!!!!!!!!!!!!!!!!!");
try{
Connection conn = DBConnection.getConnection();
customers.clear();
conn.setAutoCommit(false);
PreparedStatement stat= conn.prepareStatement("select cust_account_id,account_name from hz_cust_accounts_all where account_name is not null order by account_name asc");
// fetching customers name
ResultSet rs = stat.executeQuery();
Trace.log(Utility.ApplicationLogger, Level.INFO, Customers.class, "Execute",
"!!!!!!!!!!!!!!!!!Query Executed!!!!!!!!!!!!!!!!!!!!!!!!!");
while(rs.next()){
int id = rs.getInt("CUST_ACCOUNT_ID"); // customer id
String name = rs.getString("ACCOUNT_NAME"); // customer name
Customer c = new Customer(id,name);
customers.add(c);
}
rs.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
when i try to start application, an error comes up like that.
i cant use an image. so
Error
oracle.jdbc.pool.OracleDataSource
I dont know how Im gonna solve that, i cannot figure out why . Any help ?
Just to clarify - are you trying to use ADF Mobile (AMX pages)?
If so then you can't connect with JDBC to a remote database from the client.
You can only connect with JDBC to the local SQLite DB on your device.
To access data from remote servers you'll need to expose this data with web services and call those.

Inserted rows is not updating in database through JDBC

hi am trying to insert values into SQL database using jdbc. Current code able to connect and query sql DB. am using executeupdate to insert the values .this code is not giving any errors.but values are not getting inserted into SQL DB,even though i tired commiting the code after and before executing. how can i insert values into DB???
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import oracle.jdbc.driver.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet {
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
String p1=request.getParameter("param1");
String p2=request.getParameter("param2");
String p3=request.getParameter("param3");
String p4=request.getParameter("param4");
String p5=request.getParameter("param5");
String sql="INSERT INTO EMPLOYEES (Id,Name,Post,Salary,Location) VALUES('" + p1 + "','" + p2 + " ','" + p3 + "','" + p4 + " ','" + p5 + " ')";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
Connection con=null;
Statement stmt=null;
try
{
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE","test","Gari!2563");
stmt=con.createStatement();
stmt.executeUpdate(sql);
con.setAutoCommit(true);
}
catch(SQLException ex)
{
ex.printStackTrace();
}
finally
{
try
{
if(stmt!=null)
{
stmt.close();
stmt=null;
}
}
catch(SQLException ex)
{
ex.printStackTrace();
}
try
{
if(con!=null)
{
con.close();
con=null;
}
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
PrintWriter out = response.getWriter();
out.println("done");
}
}
I AM USING jdk1.7 ,Oracle DB XE 11.2.0. Apache tomcat 7 eclipse juno EE edition.
It seems the code is wrong.
If you want to use autocommit mode, then it should be set before the query is executed (typically, after the getConnection()) - not once the query has been executed.
If you don't want to use autocommit, then you need an explicit con.commit() after the statement has been executed. You may want to have a look at the documentation for more information.
Since you have fixed your exceptions due to missing jdbc driver, it should work now.

Use of resource-manager specific transaction demarcation API in EJB 3.x

Accordinong to EJB 3.0 specification: While an instance is in a transaction, the instance must not attempt to use the resource-manager specific transaction demarcation API (e.g. it must not invoke the
commit or rollback method on the java.sql.Connection interface or on the
javax.jms.Session interface) In 13.3.3 of Specification.
I tried one example - where in BEAN managed transaction I included java.sql.Connection.commit() - created Stateless bean in NetBeans as EE5, deployed on Glassfish 3.1 and container did not complain? Bean method updates the database without any errors in Glassfish log. Is this expected behavior?
Also, there is no such restriction on using java.sql.Connection.commit() for beans with container transaction managed transactions mentioned in specification.
Thanks
Branislav
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ejb;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.Transient;
import javax.sql.DataSource;
import javax.transaction.*;
/**
*
* #author bane
*/
#Stateless
#TransactionManagement(TransactionManagementType.BEAN)
public class MySession implements MySessionRemote {
#Resource(name = "SAMPLE")
private DataSource SAMPLE;
//
#Resource UserTransaction utx;
//gore je novi kod
#Override
public String getResult() {
return "This is my Session Bean";
}
public void doSomething() {
try {
Connection conn = SAMPLE.getConnection();
Statement stmt = conn.createStatement();
String q = "select * from BOOK";
String up = "update BOOK set PRICE = PRICE + 1";
utx.begin();
int num = stmt.executeUpdate(up);
System.out.println("num: "+num);
ResultSet rs = stmt.executeQuery(q);
//is conn.commit() legal?
conn.commit();
String name = null;
int price = 0;
while (rs.next()) {
name = rs.getString(2);
price = rs.getInt(3);
System.err.println(name+" , "+price);
}
utx.commit();
} catch (SQLException ex) {
Logger.getLogger(MySession.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(MySession.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
}

Resources