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.
Related
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();
}
}
}
I am getting the following error while creating a connection to SQL Server using jdbc. THe error is :
java.sql.SQLException: No suitable driver found for jdbc:sqlserver//D-PC//SQLEXPRESS;integratedSecurity=true
Failed to make connection!
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement;
/** * * #author Jatin */ public class SQLConnect {
public Connection sqlcon(Connection conn){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
Statement stmt = null;
try{
conn = DriverManager.getConnection("jdbc:sqlserver//D-PC//SQLEXPRESS;integratedSecurity=true");
stmt = conn.createStatement();
stmt.executeUpdate("CREATE DATABASE Students");
System.out.println("Database Created");
}
catch(SQLException e){
e.printStackTrace();
}
if (conn != null) { System.out.println("You made it, take control your database now!"); } else { System.out.println("Failed to make connection!"); }
return(conn);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Connection con =null;
SQLConnect sqlcon = new SQLConnect();
con = sqlcon.sqlcon(con);
}
}
The connection to the host GUNA, named instance sqlexpress failed. Error: "java.net.SocketTimeoutException: Receive timed out". Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:237)
how to resolve this
im trying to execute a procedure which contains between others a parameter which is a collection of object (oracle). I have managed them lot of times without spring, but I'm a bit lost trying to do it with spring, althoug there is some information on the internet, I can't find a full example in order to compare my code. Spring doc has just fragments. Probably my code is wrong but i ignore why, could you help me? I'm running simplier procedures without problems. My DAO looks like this:
//[EDITED]
private SimpleJdbcCall pActualizaDia;
....
#Autowired
public void setDataSource(DataSource dataSource) {
pActualizaDia = new SimpleJdbcCall(dataSource).withCatalogName("PTR_GRUPOS_TRABAJO").withProcedureName("UPDATE_DIA");
pActualizaDia.getJdbcTemplate().setNativeJdbcExtractor(new OracleJdbc4NativeJdbcExtractor());
}
...
public Calendario updateSingle(final Calendario calendario) {
SqlTypeValue cambiosEmpresa = new AbstractSqlTypeValue() {
protected Object createTypeValue(Connection conn, int sqlType, String typeName) throws SQLException {
ArrayDescriptor arrayDescriptor = new ArrayDescriptor("TTPTR_CAMBIO_EMPRESA", conn);
Object[] collection = new Object[calendario.getCambiosEmpresa().size()];
int i = 0;
for (CeAnoEmp ce : calendario.getCambiosEmpresa()) {
collection[i++] = new STRUCT(new StructDescriptor("TPTR_CAMBIO_EMPRESA", conn), conn, new Object[] {
ce.getSQLParam1(),
//...more parameters here in order to fit your type.
ce.getSQLparamn() });
}
ARRAY idArray = new ARRAY(arrayDescriptor, conn, collection);
return idArray;
}
};
MapSqlParameterSource mapIn = new MapSqlParameterSource();
mapIn.addValue("P_ID_ESCALA", calendario.getEscala().getIdEscala());
//more simple params here
//Here it is the Oracle ARRAY working properly
pActualizaDia.declareParameters(new SqlParameter("P_CAMBIOS_EMPRESA",
OracleTypes.STRUCT, "TTPR_CAMBIO_EMPRESA"));
mapIn.addValue("P_CAMBIOS_EMPRESA",cambiosEmpresa);
//When executing the procedure it just work :)
pActualizaDia.execute(mapIn);
return null;
}
The exception I get sais
java.lang.ClassCastException: $Proxy91 cannot be cast to oracle.jdbc.OracleConnection
I've been reading more about this topic and i found that It almost seems like if using Oracle Arrays you also have to cast the connection to be an oracle connection.
However, most Spring jdbc framework classes like SimpleJDBCTemplate and StoredProcedure hide the connection access from you. Do I need to subclass one of those and override a method somewhere to get the dbcp connection and then cast it to an Oracle connection?
Thank you very much.
I've solved it finally, I've edited the post in order to have an example for anyone looking for a piece of code to solve this issue.
There are two important things to have in mind:
1) It's mandatory to set oracle extractor in jdbctemplate in order to cast properly the connection to get oracle functionality.
2) When using this extractor ojdbc and JRE version must be the same, any other case you'll get an abstractmethodinvocation exception.
Thanks anyone who tried to solve it and hope it helps.
you can use spring to call a procedure with array of collection of oracle structure : below a simple example to do this
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.sql.DataSource;
import oracle.jdbc.driver.OracleConnection;
import oracle.jdbc.driver.OracleTypes;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
public class SpringObjectMapper {
public static class SaveObjectFunction extends StoredProcedure {
final static Logger logger = LoggerFactory.getLogger(SavePackInterFunction.class);
private static final String PROC_NAME = "schema.proc_name";
private final static String ARRAY_OF_VALUE_PARAM_NAME = "ARRAY_OF_VALUE";
private final static String OUT_PARAM_NAME = "out";
public SaveObjectFunction(DataSource dataSource) {
super(dataSource, PROC_NAME);
declareParameter(new SqlParameter(ARRAY_OF_VALUE_PARAM_NAME, OracleTypes.ARRAY, "schema.array_object_type"));
compile();
}
public String execute(Collection<Model> values) {
logger.info("------------------------EnregInterlocuteurPrcedure::execute : begin----------------------------");
String message = null;
try {
OracleConnection connection = getJdbcTemplate().getDataSource().getConnection().unwrap(OracleConnection.class);
ArrayDescriptor arrayValueDescriptor = new ArrayDescriptor("schema.array_object_type", connection);
StructDescriptor typeObjeDescriptor = new StructDescriptor("schema.object_type", connection);
Object[] valueStructArray = new Object[values.size()];
int i = 0;
for (Iterator<Model> iterator = values.iterator(); iterator.hasNext();) {
Model model = (Model) iterator.next();
STRUCT s = new STRUCT(typeObjeDescriptor, connection, new Object[] {model.getAttribute1(), model.getAttribute2(), model.getAttribute3(),
model.getAttribute4(), model.getAttribute5(), model.getAttribute6(), model.getAttribute7()});
valueStructArray[i++] = s;
}
ARRAY inZoneStructArray = new ARRAY(arrayValueDescriptor, connection, valueStructArray);
Map<String, Object> inputs = new HashMap<String, Object>();
inputs.put(ARRAY_OF_VALUE_PARAM_NAME, inZoneStructArray);
Map<String, Object> out = super.execute(inputs);
message = (String) out.get(OUT_PARAM_NAME);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return message;
}
}
}
I am connecting to a Microsoft sql server database via java jdbc and having a very strange issue. Whenever I use the place holder parameters (?) in my query in the where clause and then do preparedStatement.setString(..) method my simple query takes anywhere from 4800 to 5800 milliseconds to run. When I hardcode the where clause inside of the query itself, it takes from 1 to 36 milliseconds to run. This doesn't make sense to me, because I thought using the placeholders was supposed to be faster...
The table does have a lot of rows (8 million or so), however the parameters that I pass in are just a few characters, I only pass in 2 parameters, the statement always returns 1 (or 0) rows and the data it returns is not huge. Indexes on the table don't help. Why such a HUGE time difference? 5-6 seconds is a really long time for such a query. Both of the columns in the where clause are string-type (varchar(20)) so there is no implicit type conversion on the databse side (that I know of).
I've tried a different version of the sqljdbc4.jar driver, but it's doing the same thing.
package testdbconnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws SQLException
{
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("select col1 from tableName where username = ? and password = ?");
statement.setString(1, "UName");
statement.setString(2, "PWord");
long start = System.currentTimeMillis();
ResultSet rs = statement.executeQuery();
long stop = System.currentTimeMillis();
System.out.println("took: " + (stop - start));
rs.close();
con.close();
}// end main
private static Connection getConnection()
{
Connection connection = null;
try {
// Load the JDBC driver
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(driverName);
// Create a connection to the database
String url = "jdbc:sqlserver://DBSERVERNAME;databaseName=DBNAME;";
String username = "dbUname";
String password = "dbPword";
connection = DriverManager.getConnection(url, username, password);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
} catch (SQLException e)
{
e.printStackTrace();
}
return connection;
}// end getConnection()
}
Output:
run:
took: 4891
BUILD SUCCESSFUL (total time: 5 seconds)
Now if I do this:
package testdbconnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) throws SQLException
{
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("select col1 from tableName where username = 'UName' and password = 'PWord'");
long start = System.currentTimeMillis();
ResultSet rs = statement.executeQuery();
long stop = System.currentTimeMillis();
System.out.println("took: " + (stop - start));
rs.close();
con.close();
}// end main
private static Connection getConnection()
{
Connection connection = null;
try {
// Load the JDBC driver
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(driverName);
// Create a connection to the database
String url = "jdbc:sqlserver://DBSERVERNAME;databaseName=DBNAME;";
String username = "dbUname";
String password = "dbPword";
connection = DriverManager.getConnection(url, username, password);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
} catch (SQLException e)
{
e.printStackTrace();
}
return connection;
}// end getConnection()
}
Output:
run:
took: 32
BUILD SUCCESSFUL (total time: 2 seconds)
Generally speaking, running an entirely hardcoded statement will be faster than an equivalent parameterized statement. The reason for this has to do with the execution planning of the database. When you provide all of the information from the start, the database can perform optimizations and choose shorter paths specific to the exact data you provided. When you parameterize the statement, it can only perform those optimizations that would be helpful for any value that might be inserted.
Parameterized statements can be helpful when you need to run many similar queries and want to avoid the overhead of preparing the statement every time, but for a single query on a large data set (as in your use case) a hardcoded query will be better.
import java.sql.*;
public class QBreaker
{
public static void main (String[] args)
{
Connection conn = null;
String driver="sun.jdbc.odbc.JdbcOdbcDriver";
String url="jdbc:odbc:huss";
try
{
Class.forName(driver);
conn=DriverManager.getConnection(url,"sa","admin123");
System.out.println("Connection is created");
Statement db_statement=conn.createStatement();
ResultSet rs=db_statement.executeQuery("select * from Details");
while(rs.next())
{
System.out.print("ID: "+rs.getInt("Id"));
System.out.print("\tBalance: "+rs.getString("Bal"));
}
conn.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
This is my code to connect to the database.
i have created the odbc driver n followed all the required steps in dat.
but still while running the i got this exception:
Connection is created
java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'Details'.
Process completed.
There is no such table or view named Details exists. Please verify the database.
u create Data source ? , if u not created it can u go to control panel in windows then Administrative Tools then Data Sources (ODBC) .