Dblink is not working in java - eclipse

String id="";
List list = null;
Query query = null;
Session session = getSession();
String sql = "select id from student#dblink s, location#dblink l where s.id in (select name from Employ where id='" +Id +"') and s.country_id = l.country_id and l.country_end = '"+countryEnd+"'";
query = session.createSQLQuery(sql);
System.out.println("sql.1."+sql);
list = query.list();
if(list.size()>0)
id = list.get(0).toString();
else
id= "0";
System.out.println("Stage2Ubr Id is:"+id);
return id;
Here I got exception like "org.hibernate.exception.GenericJDBCException: could not execute query". Sometimes this exception is not coming. Sometimes it's working fine without exception. This exception won't come if dblink is working fine.Please help me. How to check wheather the dblink is working fine or not?

Related

Sometimes postgres does not return records when queried remotely from JDBC Client

public static ArrayList<String[]> getDailyRecords () throws ClassNotFoundException {
ArrayList<String[]> list=new ArrayList<String[]> ();
String[] header = {"City", "Location", "Asset", "Number of Alerts", "Time spent in alerts", "Last seen temparature", "Limit"};
list.add (header);
String myDriver = "org.postgresql.Driver";
Class.forName (myDriver);
try( Connection conn = DriverManager.getConnection( ApplicationSettings.DATABASE_URL, ApplicationSettings.DATABASE_USER, ApplicationSettings.DATABASE_PASSWORD);
Statement st = conn.createStatement ();) {
conn.setAutoCommit (true);
ResultSet rs=null;
st.setFetchSize (200);
String dailyQuery="select * from sch.reports();";
rs= st.executeQuery (dailyQuery);
while (rs.next ()) {
String[] ar = new String[7];
ar[0] = rs.getString ("location");
ar[1] = rs.getString ("sublocation");
ar[2] = rs.getString ("zone");
ar[3] = rs.getString ("total_count");
ar[4] = rs.getString ("period");
String temp = rs.getString ("temparature");
ar[5] = temp;
list.add (ar);
}
conn.close ();
st.close ();
rs.close ();
}catch(Exception e){
e.printStackTrace ();
}catch(Error e){
e.printStackTrace ();
}
finally {
if(list.size ()==1){
System.out.println ("NO records found");
}else{
System.out.println ("Foudn some records");
}
return list;
}
I have a sql function, which does return records when queried locally from postgres clients. I invoke this function at scheduled timings from a java application. This worked fine for few months. But all of sudden, st.executeQuery() returning empty result set occasionally. Like 4 out of 10 attempts of executeQuery() in a day return empty resultset.
Things I have tried out:
Made sure query returns some records always. It should return 60 records.
Captured Errors,Exceptions. There were no errors seen.
Made sure JDBC connection is closed.
Debugged Postgres JDBC driver classes. Found that in cases when resultset is empty, data was not received from postgres data stream.
can size of data in tables influence query response?
Any help is kindly appreciated!
Update: SQL function definition added.
DECLARE
exception_error_code text;
exception_message text;
exception_detail text;
exception_hint text;
exception_context text;
BEGIN
RETURN QUERY
select l.name as location,sl.name as sublocation,z.name as zone,al.lim as lim,count(al.id) total_count,sum(al.timestamp_to-al.timestamp_from) period,t2.temperature temparature
from
map.location l
left join
map.sub_location sl
on l.id=sl.location_id
left join
map.zone z
on sl.id=z.sub_location_id
left join
map.subzone sz
on z.id=sz.zone_id
inner join
(select *,(info::json -> 'breach_type')::text as lim from alr.live where date(timestamp_from)= date(now() + INTERVAL '5 hours 30 minutes')) al
on sz.id= al.sub_zone_id
left join
(select subzone_id,max(nd_timestamp) as nd_timestamp from tel.temperature_sh group by subzone_id) t1
on al.sub_zone_id=t1.subzone_id
left join
tel.temperature_sh t2
on t1.subzone_id=t2.subzone_id
and t1.nd_timestamp=t2.nd_timestamp
group by l.name ,sl.name,z.name,t2.temperature , al.lim
order by l.name ,sl.name,z.name;
-- if something "breaks" do the following
EXCEPTION WHEN others THEN
get stacked diagnostics
exception_error_code = RETURNED_SQLSTATE
,exception_message = MESSAGE_TEXT
,exception_detail = PG_EXCEPTION_DETAIL
,exception_hint = PG_EXCEPTION_HINT
,exception_context = PG_EXCEPTION_CONTEXT
;
-- log exception for debugging
PERFORM public.insert_db_exception(
exception_error_code
,exception_message
,exception_detail
,exception_hint
,exception_context
);
END;

How can convert bytea to base64 in Postgres

I have now facing the problem in bytea to Base64, actually I have save the image in below query,
user_profile_pic is defind in bytea in table
Update user_profile_pic
Set user_profile_pic = (profilepic::bytea)
Where userid = userid;
after that I have select the below query,
case 1:
SELECT user_profile_pic
FROM user_profile_pic;
its return exact same as I have updated, but after passing service its display a byte format
case 2:
Select encode(user_profile_pic::bytea, 'base64')
FROM user_profile_pic;
it returns totally different result.
I want to result case 1 along with service?
its working for me, not working query if write procedure/function, i write direct code behind
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT profile_pic FROM userlog WHERE cust_id = '" + CustID + "'", conn);
Byte[] result = (Byte[])command.ExecuteScalar();
if(result.Length > 0)
{
ProfilePicture = Convert.ToBase64String(result);
ErrorNumber = 0;
ErrorMessage = "Successful operation";
}
else
{
ErrorNumber = 1;
}
conn.Close();

PostgreSQL Parameterized Insert with ADO.NET

I am using NpgSQL with PostgreSQL and ADO.NET. Forgive the simplicity of the question as I just started using PostgreSQL and NpgSQL this week.
Something like this works fine:
[Test]
public void InsertNoParameters()
{
NpgsqlConnection conn = new NpgsqlConnection("Host=localhost; Database=postgres; User ID=postgres; Password=password");
conn.Open();
IDbCommand command = conn.CreateCommand();
string sql = "INSERT INTO Customers (FirstName,LastName) VALUES ('Test','Tube')";
command.CommandText = sql;
command.ExecuteNonQuery();
conn.Close();
}
When I put in parameters I get the error message:
Npgsql.NpgsqlException : ERROR: 42703: column "_firstname" does not exist
[Test]
public void InsertWithParameters()
{
NpgsqlConnection conn = new NpgsqlConnection("Host=localhost; Database=postgres; User ID=postgres; Password=password");
conn.Open();
IDbCommand command = conn.CreateCommand();
string sql = "INSERT INTO Customers (FirstName,LastName) VALUES (_FirstName,_LastName)";
command.CommandText = sql;
var parameter = command.CreateParameter();
parameter.ParameterName = "_FirstName";
parameter.Value = "Test";
command.Parameters.Add(parameter);
parameter = command.CreateParameter();
parameter.ParameterName = "_LastName";
parameter.Value = "Tube";
command.Parameters.Add(parameter);
command.ExecuteNonQuery();
conn.Close();
}
The responses in the comments are correct:
Npgsql doesn't support _ as a parameter placeholder notation. You should be using # or : (so #FirstName or :FirstName, not _FirstName).
PostgreSQL will automatically lower-case your table and column names unless they are double-quoted. Either use lower-case names for everything (simpler) or quote identifiers in your SQL queries.
So your code should look more or less like this:
IDbCommand command = conn.CreateCommand();
string sql = "INSERT INTO Customers (first_name, last_name) VALUES (#FirstName,#LastName)";
command.CommandText = sql;
var parameter = command.CreateParameter();
parameter.ParameterName = "FirstName";
parameter.Value = "Test";
command.Parameters.Add(parameter);

Using DB2, "statement.executeQuery()" throws SqlEception only in my system

//Class UserProfileDBUtil.java
Connection conn = null;
PreparedStatement statment = null;
ResultSet rs = null;
try{
String sqlString = "select count(*) from "+AGENCY_SCHEMA_NAME+".AGENCY WHERE AGENCYCODE= ? and ENABLEDFLAG = ?";
conn = JDBCUtils.getConnection(JDBCUtils.WP_ODS);
statment = conn.prepareStatement(sqlString);
statment.setString(1, agencyCode.toUpperCase());
statment.setString(2, "Y");
rs =statment.executeQuery(); // SQL Error Line 42
while(rs.next())
{
if(rs.getInt(1) > 0 )
{
return true;
}
}
log.error("Agency for agency code "+agencyCode+" is not available or not active");
}
LOG :
com.ibm.db2.jcc.b.SqlException: DB2 SQL error: SQLCODE: -401, SQLSTATE: 42818, SQLERRMC: =
at com.ibm.db2.jcc.b.sf.e(sf.java:1680)
at com.ibm.db2.jcc.b.sf.a(sf.java:1239)
at com.ibm.db2.jcc.c.jb.h(jb.java:139)
at com.ibm.db2.jcc.c.jb.a(jb.java:43)
at com.ibm.db2.jcc.c.w.a(w.java:30)
at com.ibm.db2.jcc.c.cc.g(cc.java:161)
at com.ibm.db2.jcc.b.sf.n(sf.java:1219)
at com.ibm.db2.jcc.b.tf.gb(tf.java:1818)
at com.ibm.db2.jcc.b.tf.d(tf.java:2294)
at com.ibm.db2.jcc.b.tf.X(tf.java:508)
at com.ibm.db2.jcc.b.tf.executeQuery(tf.java:491)
at com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.executeQuery(WSJdbcPreparedStatement.java:559)
at UserProfileDBUtil.isAgencyActive(UserProfileDBUtil.java:42)
The error you're getting is a -401, which means:
The data types of the operands for the operation operator are not
compatible or comparable.
I would check and make sure that the parameters you're passing in are using the right data types. If you catch the exception, you should be able to use the exceptions Message property to see what the operator is. See here for an example.

How to use Multiple resultsets with POSTGRES JDBC?

I am using JDBC on a PostgreSQL database.
When I query for an entity in a resultset, it returns 5 rows.
Related to that entity is another entity, for which I query while i am using a row in the above resultset.
When I execute this query, the above resultset is closed.
This means that it is allowing only 1 resultset to be active on 1 connection at a time.
Previously the same code was working perfect for Oracle DB server.
Is it that I need to ask the DB admin to configure the server to allow multiple resultsets?
Or to do some change in the code?
Or is it impossible to do it in postgre?
Here is the code for more details:
Connection conn = PTSConnection.getConnection();
Statement stmt = conn.createStatement();
ResultSet lines = stmt.executeQuery("SELECT LINEID,STARTSTOPID,ENDSTOPID FROM LINES"); **//first resultset is active**
while (lines.next()){
int lineId= lines.getInt(1);
Stop ss = StopStorage.getByID(lines.getInt(2));
Stop es = StopStorage.getByID(lines.getInt(3));
ResultSet stops = stmt.executeQuery("SELECT STOPID FROM STOPSINLINES WHERE LINEID=" + lineId); **//first resultset dies**
List<Stop> lineStops = new ArrayList<Stop>();
while(stops.next()){
Stop stop = StopStorage.getByID(stops.getInt(1));
lineStops.add(stop);
}
stops.close();
Line aLine = null;
ResultSet emergencyLine = stmt.executeQuery("SELECT CAUSE, STARTTIME, ENDTIME FROM EMERGENCYLINES WHERE LINEID =" + lineId);
if(emergencyLine.next()){
String cause = emergencyLine.getString(1);
Time startTime = emergencyLine.getTime(2);
Time endTime = emergencyLine.getTime(3);
aLine = new EmergencyLine(ss, es, cause, startTime, endTime, (Stop[]) lineStops.toArray(new Stop[lineStops.size()]));
} else {
aLine = new Line(ss, es, (Stop[]) lineStops.toArray(new Stop[lineStops.size()]));
}
emergencyLine.close();
LineRepository.getInstance().addLine(aLine);
}
lines.close();
The reason is not that you are using two resultsets on the same connection, but you are re-using the same Statement object for a new query. When you run executeQuery() on a Statement instance, any previous result will be closed (I'm surprised that your code did work with Oracle...)
Simply create a new Statement object before executing the second query:
Statement stmt = conn.createStatement();
Statement nestedStmt = conn.createStatement();
ResultSet lines = stmt.executeQuery("SELECT LINEID,STARTSTOPID,ENDSTOPID FROM LINES"); **//first resultset is active**
while (lines.next()){
...
ResultSet stops = nestedStmt.executeQuery("SELECT STOPID FROM STOPSINLINES WHERE LINEID=" + lineId); **//first resultset dies**
List lineStops = new ArrayList();
while(stops.next()){
Stop stop = StopStorage.getByID(stops.getInt(1));
lineStops.add(stop);
}
stops.close();
...
ResultSet emergencyLine = nestedStmt.executeQuery("SELECT CAUSE, STARTTIME, ENDTIME FROM EMERGENCYLINES WHERE LINEID =" + lineId);
if(emergencyLine.next()){
String cause = emergencyLine.getString(1);
....
}
emergencyLine.close();
And don't for get to properly close all Statements and ResultSets !