Problem two query db2 sqlserver is not print output - jdbc

This is the correct example, which does not work:
If the LANGUAGE column is the same as the LANGUAGE COLUMN and the NLS_CLASS_NAME column is the same as the KEYWORD COLUMN
Given that they are true, if you noticed the language string I turned it into lowercase and I cut the string so that it becomes "en", since it was first ENG
You must print the language list, keyword is translation
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
//Traduzione in Db2 a SqlServer
public void getTraduzione() throws Exception {
List<DizioPt> listDizio = new ArrayList<DizioPt>();
List<ClassHdrNls> listHdr = new ArrayList<ClassHdrNls>();
String className = "";
String language = "";
String nlsClassName = "";
String lingua = "";
String keyword = "";
String traduzione = "";
Database database = new Database();
// Db2
Connection dbConnectionDb2 = null;
Statement statementDb2 = null;
// SqlServer
Connection dbConnectionSqlServer = null;
Statement statementSqlServer = null;
// Query Db2
String queryDb2 = "select * from THERA.CLASS_HDR_NLS WHERE
THERA.CLASS_HDR_NLS.LANGUAGE='en'";
// Query SqlServer
String querySqlServer = "select * from DIZIOPT WHERE
DIZIOPT.LINGUA='ENG'";
try {
// Connessione --> SqlServer
dbConnectionSqlServer = database.getConnectionSqlServer();
statementSqlServer = dbConnectionSqlServer.createStatement();
// Connessione -->Db2
dbConnectionDb2 = database.getConnectionDb2();
statementDb2 = dbConnectionDb2.createStatement();
// Risultato SqlServer
ResultSet rsSqlServer = statementSqlServer.executeQuery(querySqlServer);
// Risultato Db2
ResultSet rsDb2 = statementDb2.executeQuery(queryDb2);
while (rsSqlServer.next() && rsDb2.next()) {
ClassHdrNls classHdrNls = new ClassHdrNls();
className = rsDb2.getString("CLASS_NAME");
classHdrNls.setClassName(className);
language = rsDb2.getString("LANGUAGE");
classHdrNls.setLanguage(language);
nlsClassName = rsDb2.getString("NLS_CLASS_NAME");
classHdrNls.setNlsClassName(nlsClassName);
listHdr.add(classHdrNls);
DizioPt diziopt = new DizioPt();
lingua = rsSqlServer.getString("LINGUA");
diziopt.setLingua(lingua);
keyword = rsSqlServer.getString("KEYWORD");
diziopt.setKeyword(keyword);
traduzione = rsSqlServer.getString("TRADUZIONE");
diziopt.setTraduzione(traduzione);
listDizio.add(diziopt);
for (int i = 0; i < listHdr.size(); i++) {
for (int j = 0; j < listDizio.size(); j++) {
if (listHdr.get(i).getNlsClassName().equalsIgnoreCase(listDizio.get(j).getKeyword())
&& listHdr.get(i).getLanguage()
.equalsIgnoreCase(listDizio.get(j).getLingua().toLowerCase().substring(0, 2))) {
System.out.println("Class name: " + listHdr.get(i).getClassName());
System.out.println("Lingua: " + listHdr.get(i).getLanguage());
System.out.println("Testo: " + listHdr.get(i).getNlsClassName());
System.out.println("Traduzione: " + listDizio.get(j).getTraduzione());
}
}
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statementDb2 != null && statementSqlServer != null) {
statementDb2.close();
statementSqlServer.close();
}
if (dbConnectionDb2 != null && dbConnectionSqlServer != null) {
dbConnectionDb2.close();
dbConnectionSqlServer.close();
}
}
}

Related

Got Null result from Oracle even though the real result are decimal value

I am new to Oracle in Visual Studio,
I used Oracle.ManagedDataAccess as my reference,
The case is whenever I tried to retrieve decimal value from arithmetic in Oracle query, Its always return null
e.g
SELECT 26/3 FROM DUAL < ---- This code return null in my visual studio but has a value in TOAD.
Did I do it wrong ?
Here is my code to retrieve the value
List<object[]> result = new List<object[]>();
OracleDataReader data;
string constr = ConfigurationManager.ConnectionStrings["OraConnection"].ConnectionString;
using (OracleConnection con = new OracleConnection(constr))
{
string query = QueryString;
using (OracleCommand cmd = new OracleCommand(query))
{
cmd.Connection = con;
con.Open();
data = cmd.ExecuteReader();
try
{
if (data.HasRows)
{
while (data.Read())
{
object[] itemData = new object[data.FieldCount];
//Dictionary<string, string> itemData = new Dictionary<string, string>();
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
if (typeof(string) == type)
{
itemData[i] = data.GetString(i);
}
if (typeof(DateTime) == type)
{
itemData[i] = data.GetDateTime(i);
}
if (typeof(int) == type)
{
itemData[i] = data.GetInt32(i);
}
if (typeof(decimal) == type)
{
itemData[i] = data.GetDecimal(i);
}
if (typeof(bool) == type)
{
itemData[i] = data.GetBoolean(i);
}
if (typeof(TimeSpan) == type)
{
itemData[i] = data.GetTimeSpan(i);
}
if (typeof(Single) == type)
{
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
}
}
result.Add(itemData);
}
}
else
{
Console.WriteLine("Rows not found.");
}
}
finally
{
data.Close();
}
con.Close();
}
}
return result;
UPDATED : It got null just for division which has decimal value. Addition, Substraction, multiplication has no issue
It seems your data type doesn't match any of your if expressions. As there is no default branch, itemData[i] remains null. I suggest something like the following to find the gap:
for (int i = 0; i < data.FieldCount; i++)
{
Type type = data.GetValue(i).GetType();
switch(type)
{
case typeof(string):
itemData[i] = data.GetString(i);
break;
case typeof(DateTime):
itemData[i] = data.GetDateTime(i);
break;
case typeof(int):
itemData[i] = data.GetInt32(i);
break;
case typeof(decimal):
itemData[i] = data.GetDecimal(i);
break;
case typeof(bool):
itemData[i] = data.GetBoolean(i);
break;
case typeof(TimeSpan):
itemData[i] = data.GetTimeSpan(i);
break;
case typeof(Single):
itemData[i] = Convert.ToDecimal(data.GetOracleDecimal(i).ToString());
break;
default:
MessageBox.Show("Unknown type " + type.Name);
break;
}
}
So, I got an advice to edit the oracle query
From (e.g.)
SELECT 26/7 FROM DUAL
TO
SELECT TO_CHAR(26/7) FROM DUAL
And yes it works
But still, I don't know why

Silverlight some wcf problems

I have created a WCF Service which is called many times,
An example of a call
This Service will do a call to a Database. Lets say in my Client I do have a List with 200 Values. Every Value will match a Database Entry. Every Database Entry does have 10 Values. Now what I do is the following. I select some of the list entrys and call in a loop the WCF Service.
I have 2 Issues
First: the UI will hang for that time the WCF Calls are made
Second: The data will come back step by step, how can I collect them and send it back when all calls are completed?
Please excuse any typos I made, my english is not the best.
Here is my source code
[ServiceContract(Namespace = "")]
[SilverlightFaultBehavior]
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.PerCall)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[OperationContract]
public List<string> GetData(string sWert1, string sWert2)
{
List<string> realtimanswer = new List<string>();
string applicationPath = HostingEnvironment.MapPath("~/Configuration");
cIniReader _ini = new cIniReader(applicationPath + #"\config.ini");
string connectionString = _ini.ReadString("Database", "ConnectionString", "");
OracleConnection connection = new OracleConnection();
connection.ConnectionString = connectionString;
try
{
connection.Open();
OracleCommand cmd = connection.CreateCommand();
cmd = new OracleCommand("GETDATA", connection);
cmd.Parameters.Clear();
OracleParameter param1 = new OracleParameter("PI_Wert1", OracleDbType.Varchar2);
OracleParameter param2 = new OracleParameter("PI_Wert2", OracleDbType.Varchar2);
OracleParameter param3 = new OracleParameter("PO_Wert3", OracleDbType.Int16);
OracleParameter param4 = new OracleParameter("PO_Wert3", OracleDbType.Int16);
OracleParameter param5 = new OracleParameter("PO_Wert4", OracleDbType.Int16);
param1.Value = sWert1;
param2.Value = sWert2;
param1.Direction = System.Data.ParameterDirection.Input;
param1.Size = 4096;
param2.Direction = System.Data.ParameterDirection.Input;
param2.Size = 4096;
param3.Direction = System.Data.ParameterDirection.Output;
param3.Size = 4096;
param4.Direction = System.Data.ParameterDirection.Output;
param4.Size = 4096;
param5.Direction = System.Data.ParameterDirection.Output;
param5.Size = 4096;
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
cmd.Parameters.Add(param3);
cmd.Parameters.Add(param4);
cmd.Parameters.Add(param5);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//cmd.CommandTimeout = 30;
int test = cmd.ExecuteNonQuery();
string returnCode = cmd.Parameters[17 - 1].Value.ToString();
if (returnCode == "OK")
{
string sErg1 = cmd.Parameters[3 - 1].Value.ToString();
realtimanswer.Add(sErg1);
string sErg2 = cmd.Parameters[4 - 1].Value.ToString();
realtimanswer.Add(sErg2);
string sErg3 = cmd.Parameters[5 - 1].Value.ToString();
realtimanswer.Add(sErg3);
string sErg4 = cmd.Parameters[6 - 1].Value.ToString();
realtimanswer.Add(sErg4);
string sErg5 = cmd.Parameters[7 - 1].Value.ToString();
realtimanswer.Add(sErg5);
}
}
catch (Exception exp)
{
cDebugLog.Log("Error in Function: GetData " + exp.Message + " StackTrace: " + exp.StackTrace);
connection.Close();
}
connection.Close();
return realtimanswer;
}
}
I call this with this Code
void Button1_Click(object sender, EventArgs e)
{
busyRealTimeViewPage.IsBusy = true;
try
{
string url = Application.Current.Host.Source.AbsoluteUri;
url = url.Replace("/ClientBin/ICWeb.xap", "/DBService.svc");
var proxy_GetRealTime_DBService = new DBServiceReference.DBServiceClient();
proxy_GetRealTime_DBService.Endpoint.Address = new System.ServiceModel.EndpointAddress(url);
proxy_GetRealTime_DBService.GetDataCompleted += new EventHandler<DBServiceReference.GetDataCompletedEventArgs>(proxy_GetRealTime_DBService_GetDataCompleted);
for (int i = 0; i < lstRealtime.Items.Count; i++)
{
if ((lstRealtim.ItemsSource as ObservableCollection<ListOfData>)[i].IsSelected == true)
{
object[] w_toread = new object[5];
string sWrk = (lstMappedWorkgroups.ItemsSource as ObservableCollection<ListOfWorkgroups>)[i].Content;
w_toread[0] = sDat;
w_toread[1] = sDat + "_DE";
w_toread[2] = sDat + "_FR";
proxy_GetRealTime_DBService.GetDataAsync(w_toread[1].ToString(), "current", w_toread[1]);
proxy_GetRealTime_DBService.GetDataAsync(w_toread[2].ToString(), "current", w_toread[2]);
}
}
}
catch (Exception exp)
{
cDebugLog logger = new cDebugLog();
logger.LogMessage("Error in Function: Button1_Click " + exp.Message + " StackTrace: " + exp.StackTrace);
}
and now here is the rest of it
void proxy_GetRealTime_DBService_GetDataCompleted(object sender, DBServiceReference.GetMarqueeDataCompletedEventArgs e)
{
try
{
string help = e.UserState.ToString();
string sWrktoView = cStringFunctions.Left(e.UserState.ToString(), help.Length - 3);
// string sWrktoView = (lstMappedWorkgroups.ItemsSource as ObservableCollection<ListOfWorkgroups>)[i].Content;
string sWrktoViewDE = sWrktoView + "_DE";
string sWrktoViewFR = sWrktoView + "_FR";
if ((sWrktoViewDE == e.UserState.ToString()) || (sWrktoViewFR == e.UserState.ToString()))
{
if (!(toView.Any(wrk => wrk.Workgroup == sWrktoView)))
{
if (sWrktoViewDE == e.UserState.ToString())
{
toView.Add(new RealtTime(sWrktoView, sWrktoViewDE, e.Result[0], e.Result[1], e.Result[2], e.Result[3], e.Result[4], e.Result[5], e.Result[6], e.Result[7], e.Result[8], e.Result[9], e.Result[10], e.Result[11], e.Result[12], e.Result[13], sWrktoViewFR, "", "", "", "", "", "", "", "", "", "", "", "", "", ""));
}
if (sWrktoViewFR == e.UserState.ToString())
{
toView.Add(new RealtTime(sWrktoView, sWrktoViewDE, "", "", "", "", "", "", "", "", "", "", "", "", "", "", sWrktoViewFR, e.Result[0], e.Result[1], e.Result[2], e.Result[3], e.Result[4], e.Result[5], e.Result[6], e.Result[7], e.Result[8], e.Result[9], e.Result[10], e.Result[11], e.Result[12], e.Result[13]));
}
}
}
if (sWrktoViewFR == e.UserState.ToString())
{
var wrkFR = toView.FirstOrDefault(x => x.WorkgroupFR == sWrktoViewFR);
if (wrkFR != null)
{
wrkFR.WorkgroupFR = sWrktoViewFR;
wrkFR.erg1FR = e.Result[0];
wrkFR.erg2FR = e.Result[1];
wrkFR.erg3FR = e.Result[2];
wrkFR.erg4FR = e.Result[3];
wrkFR.erg5FR = e.Result[4];
// fill with other data
}
}
if (sWrktoViewDE == e.UserState.ToString())
{
var wrkDE = toView.FirstOrDefault(x => x.WorkgroupDE == sWrktoViewDE);
if (wrkDE != null)
{
wrkDE.WorkgroupDE = sWrktoViewDE;
wrkDE.erg1DE = e.Result[0];
wrkDE.erg2DE = e.Result[1];
wrkDE.erg3DE = e.Result[2];
wrkDE.erg4DE = e.Result[3];
wrkDE.erg5DE = e.Result[4];
// fill with other Data
}
}
dgridRealTimeView.ItemsSource = null;
dgridRealTimeView.ItemsSource = toView;
busyRealTimeViewPage.IsBusy = false;
}
catch (Exception exp)
{
cDebugLog logger = new cDebugLog();
logger.LogMessage("Methode: proxy_GetRealTime_DBService_GetDataCompleted: " + exp.Message + " StackTrace: " + exp.StackTrace);
}
}
I hope someone can help me out.
Regards
Martin
This call
for (int i = 0; i < lstRealtime.Items.Count; i++)
can take a long time if the there are a lot of items in the list.
You should consider creating a new method on the WCF Service to do all the operations and then returning the result.
public List<string> GetData(string[] sWert1, string[] sWert2)
{
}

j2me midlet chinese character display message garbled

My J2ME midlet could retrieves message in Chinese character from a PHP server but it's garbled. The server basically returns the response string and by detecting the first 2 characters. AA = good, anything else indicates error of which the message is to be passed to the calling function for display
InputStream is = null;
StringBuffer sb = null;
String str = "";
HttpConnection http = null;
DataOutputStream dos = null;
try
{
URL = login.getURL();
URL += ctlFunction + "/" + uriStr;
URL = EncodeURL(URL);
//System.out.println(URL);
if(!ctlFunction.equals("login"))
{
msg += "&user=" + login.getUsername();
msg += "&token=" + login.getToken();
}
msg += "&lang=" + System.getProperty("microedition.locale");
// establish the connection
http = (HttpConnection) Connector.open(URL);
http.setRequestMethod(HttpConnection.POST);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
http.setRequestProperty("Content-length", ""+EncodeURL(msg).getBytes().length);
dos = http.openDataOutputStream();
byte[] request_body = EncodeURL(msg).getBytes();
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// server response
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
is = http.openDataInputStream();
int length = (int) http.getLength();
if (length != -1)
{
// Read data in one chunk
byte serverData[] = new byte[length];
is.read(serverData);
str = new String(serverData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
}
else
{
networkError();
}
}
catch (Exception e)
{
System.err.println("Error3: " + e.toString());
networkError(e.toString());
}
finally
{
if (is != null)
is.close();
if (!str.equals(""))
post = str;
else
networkError();
if (http != null)
http.close();
}
if (post != null)
{
String fate = post.substring(0, 2);
if(fate.equals("AA"))
{
if(ctlFunction.equals("login"))
{
String rawPost = post.substring(2);
Vector v = new Vector();
int index = 0;
//find the first occurrence of the SPLITTER
int endIndex = rawPost.indexOf(SPLITTER, index);
String item = "";
//extract the items until the end of the last SPLITTER found in the rawPost string
while(endIndex != -1)
{
item = rawPost.substring(index, endIndex);
index = endIndex + 1;
endIndex = rawPost.indexOf(SPLITTER, index);
v.addElement(item);
}
//extract the rest of the rawPost (the text item)
item = rawPost.substring(index);
v.addElement(item);
String[] ret = new String[v.size()];
v.copyInto(ret);
login.setToken(ret[0]);
login.setToday(ret[1]);
login.setNextDrawDay(ret[2]);
}
midlet.returnResults(post.substring(2), getCurrentDisplay(), ctlFunction);
}
else
{
String errmessage = post.substring(2);
System.out.println(post);
midlet.showInfo(post, getCurrentDisplay());
}
}
else
{
networkError();
}
On the PHP server, I have set the header to UTF-8 encoding
<?php header("Content-Type:text/plain; charset=utf-8"); ?>
What could possibly be wrong?
I found that this user has the same problem and it's been answered
Reading UTF8 strings from a server through http using MIDP. Kudos to the answer.
I basically edited my MIDP code from
// is = http.openDataInputStream();
// int length = (int) http.getLength();
// if (length != -1)
// {
// // Read data in one chunk
// byte serverData[] = new byte[length];
// is.read(serverData);
// str = new String(serverData);
// }
// else // Length not available...
// {
// ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
// int ch;
// while ((ch = is.read()) != -1)
// bStrm.write(ch);
//
// str = new String(bStrm.toByteArray());
// bStrm.close();
// }
to
Reader r = new InputStreamReader(http.openInputStream(), "UTF-8");
int ch;
while((ch = r.read()) != -1)
str = str + (char)ch;
just wondering though why does reading bytes messes up the UTF-8 characters?

Issue in reading google text document

I could get the handle to the google text doc i needed. I am now stuck at how to read the contents.
My code looks like:
GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
oauthParameters.setOAuthConsumerKey(Constants.CONSUMER_KEY);
oauthParameters.setOAuthConsumerSecret(Constants.CONSUMER_SECRET);
oauthParameters.setOAuthToken(Constants.ACCESS_TOKEN);
oauthParameters.setOAuthTokenSecret(Constants.ACCESS_TOKEN_SECRET);
DocsService client = new DocsService("sakshum-YourAppName-v1");
client.setOAuthCredentials(oauthParameters, new OAuthHmacSha1Signer());
URL feedUrl = new URL("https://docs.google.com/feeds/default/private/full/");
DocumentQuery dquery = new DocumentQuery(feedUrl);
dquery.setTitleQuery("blood_donor_verification_template_dev");
dquery.setTitleExact(true);
dquery.setMaxResults(10);
DocumentListFeed resultFeed = client.getFeed(dquery, DocumentListFeed.class);
System.out.println("feed size:" + resultFeed.getEntries().size());
String emailBody = "";
for (DocumentListEntry entry : resultFeed.getEntries()) {
System.out.println(entry.getPlainTextContent());
emailBody = entry.getPlainTextContent();
}
Plz note that entry.getPlainTextContent() does not work and throws object not TextContent type exception
finally i solved it as:
for (DocumentListEntry entry : resultFeed.getEntries()) {
String docId = entry.getDocId();
String docType = entry.getType();
URL exportUrl =
new URL("https://docs.google.com/feeds/download/" + docType
+ "s/Export?docID=" + docId + "&exportFormat=html");
MediaContent mc = new MediaContent();
mc.setUri(exportUrl.toString());
MediaSource ms = client.getMedia(mc);
InputStream inStream = null;
try {
inStream = ms.getInputStream();
int c;
while ((c = inStream.read()) != -1) {
emailBody.append((char)c);
}
} finally {
if (inStream != null) {
inStream.close();
}
}
}

System.IndexOutOfRangeException: Cannot find column

I am implementing gridview sorting which is part of a user control. Below code gives me Indexoutofrange error.
The error message is at
dtView.Sort = strSort;
Errormessage:
System.IndexOutOfRangeException: Cannot find column TEXT_COUNTY_ID.
Can anyone point out what I am doing wrong?
protected void SortGridData_Hkl(Object sender, GridViewSortEventArgs e)
{
GridView _dgd_work_onoff = (GridView)Page.FindControl("bodyuc$dgd_work_onoff");
DataSet dstemp;
DataView dtView;
if (ViewState["dsfetchResults"] != null)
{
dstemp = (DataSet)ViewState["dsfetchResults"];
string strSortOrder = ViewState["SortOrder"].ToString();
if (strSortOrder == "DESC")
{
strSortOrder = "ASC";
ViewState["SortOrder"] = strSortOrder;
}
else
{
strSortOrder = "DESC";
ViewState["SortOrder"] = strSortOrder;
}
string strSort = e.SortExpression.ToString() + " " + strSortOrder;
ViewState["SortString"] = strSort;
dtView = dstemp.Tables[0].DefaultView;
dtView.Sort = strSort;
if (dtView.Count != 0)
{
if (_dgd_work_onoff != null)
{
_dgd_work_onoff.DataSource = dtView;
_dgd_work_onoff.DataBind();
}
}
}
'dsfetchResults' is suppose to contain the data from the database.
Got the solution. The column name was different from that of the database column.

Resources