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

//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.

Related

Dblink is not working in java

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?

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);

PostgreSQL, Get database exists with Npgsql

I cant get reliable checking for database existence in NET/Npgsql at my program startup.
Here is code:
Public Function dbExists(ByVal _dbName As String) As Boolean
Dim retval As Boolean = False
Using mCon As New NpgsqlConnection(String.Format( _
"Server={0};Port={1};User Id={2};Password={3};", _
dbserver, dbport, "postgres", dbpass))
Try
mCon.Open()
Using nCom = New NpgsqlCommand("SELECT 1 FROM pg_database WHERE datname='" + _dbName + "'", mCon)
retval = CBool(nCom.ExecuteScalar())
End Using
Catch ex As Exception
retval = False
End Try
End Using
Return retval
End Function
This function return True no matter database exists or not.
I also try with null checking on ExecuteScalar, getting Count(*) and all what I can without better result.
What to do to get it working?
Null checking on 'ExecuteScalar()' works for me (PostgreSQL 9.3 and Npgsql 2.0.12).
Are you checking 'ExecuteScalar() == null'?
ExecuteScalar will return a .NET null not DBNull.Value (since it is not a record with a null value, it signifies no matching result).
I'm not a VB person but here's how I achieved it in C#:
bool dbExists;
using (NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=postgres;User Id=postgres;Password=testpass"))
{
conn.Open();
string cmdText = "SELECT 1 FROM pg_database WHERE datname='temp'";
using (NpgsqlCommand cmd = new NpgsqlCommand(cmdText, conn))
{
dbExists = cmd.ExecuteScalar() != null;
}
}

how to write native query in jpa

I am getting the following error when I press the search button:
An Error Occurred:
Exception [EclipseLink-4002] (Eclipse Persistence Services -
2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal
Exception: java.sql.SQLException: Missing IN or OUT parameter at
index:: 1 Error Code: 17041 Call: SELECT * FROM CRM_DAILY_SHEET WHERE
to_char(reported_on,'dd-MM-yy') = :reportedOn Query:
ReadAllQuery(referenceClass=CrmDailySheet sql="SELECT * FROM
CRM_DAILY_SHEET WHERE to_char(reported_on,'dd-MM-yy') = :reportedOn")
Code:
public List < CrmDailySheet > searchres() throws Exception {
SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yy");
Date d1 = searchsht.getReportedOn();
String date_to_string = ddMMMyyFormat.format(d1);
return crmsrvc.searchDailysht(date_to_string);
}
try {
Query query = em.createNativeQuery("SELECT * FROM CRM_DAILY_SHEET
WHERE to_char (reported_on,'dd-MM-yy') = :reportedOn", CrmDailySheet.class);
query.setParameter("reportedOn", reportedOn);
List < CrmDailySheet > res = query.getResultList();
return res;
} finally {
em.close();
}
Can anyone find the solution please?
You are trying to use the JPQL parameter syntax (the ":reportedOn") with a native query. Try using ? instead and set the parameter value by position, e.g.:
Query query = em.createNativeQuery("SELECT * FROM CRM_DAILY_SHEET
WHERE to_char (reported_on,'dd-MM-yy') = ?", CrmDailySheet.class);
query.setParameter(1, reportedOn);

DB2DataAdapter.Fill(dataset) throws error "SQL0901N (Reason "CPF4273".) SQLSTATE=58004"

My application is Dot Net based.I am using VS My application uses IBm DB2 at its backend.
My Query is
SELECT A, B FROM SERVER.D WHERE A IN
(SELECT C FROM SERVER.E WHERE X = '01OBPP' AND Y= 'U' AND Z= '1')
A,B,C,X,Y,Z-COLUMN NAME, SERVER- SERVER NAME, D AND E -TABLE NAME
PFB the code-
DB2DataAdapter dbAdapter = null;
DB2Connection dbConn = null;
DB2Command dbCommand;
DataSet dsReturnDataSet ;
dbConn = new DB2Connection(connectionString);
if (dbConn.State == ConnectionState.Closed) dbConn.Open();
dsReturnDataSet.Clear();
dbCommand = GetCommand();
dbCommand.CommandText = queryString;
dbCommand.Connection = dbConn;
dbAdapter = new DB2DataAdapter((DB2Command)dbCommand);
dbAdapter.Fill(dsReturnDataSet);
return dsReturnDataSet;
The GetCommand() method has the following statement
DB2Command dbCommand;
dbCommand = null;
dbCommand = new DB2Command();
dbCommand.CommandType = CommandType.Text;
dbCommand.CommandTimeout = 30;
return dbCommand;
While it hits the line 'dbAdapter.Fill(dsReturnDataSet);' it stucks there for a very long time and after that it throws the error
"ERROR [58004] [IBM][AS] SQL0901N The SQL statement failed because of
a non-severe system error. Subsequent SQL statements can be processed.
(Reason "CPF4273".) SQLSTATE=58004"
Please provide some pointers.
i will be very grateful if any one can give some pointers as to hoW to solve this error.
Check your database log. There should be a db2diag.log file in the db2dump directory under the instance's sqllib directory. Search this file for the above error and it should contain the root cause (that non-severe system error) that it refers to.