can xpath be use this way? - java

System.out.println("The U value: " + u);
Statement stmt3 = null;
ResultSet srs3 = null;
List28 = new ArrayList<String>();
stmt3 = conn.createStatement();
String query = "SELECT [USERS_SYS_ID],[GROUPS_SYS_ID] as groupID FROM [USERS_GROUPS] WHERE [USERS_SYS_ID] = " + (u + 1);
srs3 = stmt3.executeQuery(query);
while (srs3.next()) {
List28.add(srs3.getString("groupID"));
}
System.out.println("Group ID: " + List28);
String z = "0";
z = null;
z = ("T_GROUP_" + List28.get(0));
driver.findElement(By.xpath(".//*[#id=z")).click();
System.out.println("Group ID: " + driver.findElement(By.xpath(".//*[#id=z]")));
Given that the value of u is 2 and List28 give a return 2.
Is it possible to run click on the xpath like this
driver.findElement(By.xpath(".//*[#id=z")).click();

Yes, it is possible using the String.format()
String xpathExpression = String.format(".//*[#id='%s']", z);
driver.findElement(By.xpath(xpathExpression)).click();
or simply
driver.findElement(By.xpath(".//*[#id='"+z+"']")).click();

Related

Best way to print data from two columns of mySQL database to jTextfield one after another

I am trying to make a program in which i read an input from the user i.e. in the textfield named gname and store its value to a string called grammar. Now this input is what sorts my output from the database.
Database looks like this
So when user enters G1 in the textfield it should display records in such a way
A->ab,A-ab,B->b
But it only shows 1st element when i use if(myRs.next) and last one if i use while(myRs.next().
current output is
Here is the code for this:
its all in try catch block
String grammar = gname.getText();
myCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/grammar", "root", "");
JOptionPane.showMessageDialog(rootPane, "Connected to database");
mystmt = myCon.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String query = "SELECT starting_symbol, value from starting_symbol where grammar= '" + grammar + "'";
String query2 = "SELECT non_terminals, terminals from input_values where grammar= '" + grammar + "'";
mystmt.addBatch(query);
mystmt.addBatch(query2);
myCon.setAutoCommit(false);
mystmt.addBatch(query);
mystmt.addBatch(query2);
myRs = mystmt.executeQuery(query);
while (myRs.next()) {
String s = myRs.getString("starting_symbol");
String val = myRs.getString("value");
output.setText(s + "-> " + val);
}
myRs = mystmt.executeQuery(query2);
ArrayList<String> list_one = new ArrayList<String>();
ArrayList<String> list_two = new ArrayList<String>();
while (myRs.next()) {
list_one.add(myRs.getString("non_terminals"));
list_two.add(myRs.getString("terminals"));
for (int i = 0; i < list_one.size(); i++) {
output_2.setText(list_one.get(i) + "->" + list_two.get(i));
}
}
Please help me in getting the correct outut
Use StringBuilder Luke
StringBuilder b = new StringBuilder();
while (myRs.next()) {
String s = myRs.getString("starting_symbol");
String val = myRs.getString("value");
if (b.length() > 0) {
b.append(',');
}
b.append(s + "-> " + val);
}
output.setText(b.toString());
And do the same for output_2 field
Your code snippet can be just like the following:
StringBuilder sb = new StringBuilder();
while (myRs.next()) {
if (sb.length() > 0) sb.append(",");
sb.append(myRs.getString("non_terminals"))
.append("->")
.append(myRs.getString("terminals"));
}
Instead of calling output_2.setText multiple times that only set the text to be the last fetch value of non_terminals -> terminals in this case B->b.

Trouble Updating a Table Row in Java

Connection conn = SqlConnection.getConnection("jdbc:mysql://localhost:3306/stocks");
Statement statement = conn.createStatement();
File path = new File("/Users/Zack/Desktop/JavaDB/BALANCESHEETS");
for(File file: path.listFiles()) {
if (file.isFile()) {
String fileName = file.getName();
String ticker = fileName.split("\\_")[0];
if (ticker.equals("ASB") || ticker.equals("FRC")) {
if (ticker.equals("ASB")) {
ticker = ticker + "PRD";
}
if (ticker.equals("FRC")) {
ticker = ticker + "PRD";
}
}
//CSVReader reader = new CSVReader(new FileReader(file));
//List entries = reader.readAll();
//ArrayList<String> entry = new ArrayList<String>();
Reader reader = new BufferedReader(new FileReader(file));
StringBuilder builder = new StringBuilder();
int c;
while ((c = reader.read()) != -1) {
builder.append((char) c);
}
String string = builder.toString();
ArrayList<String> stringResult = new ArrayList<String>();
if (string != null) {
String[] splitData = string.split("\\s*,\\s*|\\n");
for (int i = 0; i <splitData.length; i++) {
if (!(splitData[i] == null) || !(splitData[i].length() ==0)) {
stringResult.add(splitData[i].trim());
}
}
}
String columnName = null;
int yearCount = 0;
for (int i = 0; i < stringResult.size(); i++) {
int sL = stringResult.get(i).length();
for (int x = 0; x < sL; x++) {
if (Character.isLetter(stringResult.get(i).charAt(x))) {
yearCount = 0;
System.out.println("index: " + i);
columnName = stringResult.get(i);
columnName = columnName.replace(" ", "_");
System.out.println(columnName);
i++;
break;
}
}
yearCount++;
String value = stringResult.get(i);
System.out.println("Year: " + stringResult.get(yearCount) + " Value: " + value + " Stock: " + ticker + " Column: " + columnName );
if (!(columnName == null)) {
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUE ('" + ticker + "','" + stringResult.get(yearCount) + "','" + value + "')";
String writeValues2 = "UPDATE BalanceSheet "
+ "SET ticker = '" + ticker + "', "
+ "Year = '" + stringResult.get(yearCount) + "', "
+ columnName + " = '" + value + "' "
+ "WHERE ticker = '" + ticker + "'";
statement.executeUpdate(writeValues2);
}
}
Towards the bottom of the code are two queries I tried, I'm trying to get all data organized by ticker and year into a table, "writeColumns" works but it's making a new row for every new "value" put into "columnName". My second attempt "writeColumns2" doesn't do anything.
I want to update the same row with a certain year for all values and then move onto the next year, then next ticker.
If I have understood your question correctly, you want to insert a row if it doesn't exists but update the values if it already does. You need to use ON DUPLICATE KEY UPDATE
String writeValues = "INSERT INTO BalanceSheet (ticker, Year, " + columnName + ") "
+ "VALUES (?,?,?) "
+"ON DUPLICATE KEY UPDATE " + columnName +"=?";
Statement statement = conn.prepareStatement(writeValues);
statement.setString(1,ticker);
statement.setString(2,stringResult.get(yearCount));
statement.setString(3, value);
This will solve your immidiate problem provided you create a UNIQUE index on ticker,year
However there are lot's of other issues here.
An update for each column - Currently you are doing an insert/update for each column on the table. What you are supposed to do is to insert update all the columns at one.
You are not using prepared statements addressed in my code sample
You shouldn't be doing this at all the best way to batch process data is to use MYSQL's built in LOAD DATA INFILE command. If your data is not in a format that can be easily imported into mysql, what your Java code can do is to transform it into a format that can be. Such a code will be a lot simpler and neater than what you have now

JDBC - Query returns no values

I am trying to make a query that returns a simple series of results using JDBC on a java class. The Query only needs 1 join for it to work yet, for some reason, it does not return any values. However, when this query is ran on the Oracle SQL Developer, the correct results are shown. below is the code i am currently using.
To Access Database
query = "select h.house_id, h.house_address, h.house_type, h.status, l.firstname, l.surname, h.price_per_month "
+ "from houses_tbl h join landlord_tbl l on l.landlord_id = h.landlord_id";
conn = connectToDatabase();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
System.out.println(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
To Retrieve Data
response.setContentType("application/json");
fullJsonString = "{";
fullJsonString += "\"houses\":[";
ArrayList<HouseObj> allHouses = new ArrayList<HouseObj>();
try {
while (rs.next()) {
int houseID = rs.getInt(1);
Struct address = (Struct) rs.getObject(2);
Object[] taskAddress = address.getAttributes();
String houseAddressStreet = taskAddress[0].toString();
String houseAddressTown = taskAddress[1].toString();
String houseAddressCounty = taskAddress[2].toString();
String houseAddressCountry = taskAddress[3].toString();
String houseAddressPostcode = taskAddress[4].toString();
String houseFullAddress = houseAddressStreet + ", "
+ houseAddressTown + ", " + houseAddressCounty
+ ", " + houseAddressCountry + ", "
+ houseAddressPostcode;
String type = rs.getString(3);
String status = rs.getString(4);
String landlord = rs.getString(5)+" "+rs.getString(6);
int price = rs.getInt(7);
HouseObj newClient = new HouseObj(houseID,
houseFullAddress, type, status, landlord, price);
allHouses.add(newClient);
}
System.out.println("Number Of Houses : "+allHouses.size());
for (int i = 0; i < allHouses.size(); i++) {
if (i == allHouses.size() - 1) {
fullJsonString += "{\"id\":\""
+ allHouses.get(i).getHouseId() + "\","
+ "\"address\":\""
+ allHouses.get(i).getAddress() + "\","
+ "\"type\":\""
+ allHouses.get(i).getType() + "\","
+ "\"status\":\""
+ allHouses.get(i).getStatus() + "\","
+ "\"landlord\":\""
+ allHouses.get(i).getLandlord() + "\","
+ "\"price\":\""
+ allHouses.get(i).getPrice() + "\"}";
} else {
fullJsonString += "{\"id\":\""
+ allHouses.get(i).getHouseId() + "\","
+ "\"address\":\""
+ allHouses.get(i).getAddress() + "\","
+ "\"type\":\""
+ allHouses.get(i).getType() + "\","
+ "\"status\":\""
+ allHouses.get(i).getStatus() + "\","
+ "\"landlord\":\""
+ allHouses.get(i).getLandlord() + "\","
+ "\"price\":\""
+ allHouses.get(i).getPrice() + "\"},";
}
}
fullJsonString += "]}";
} //Catch Exception Below
Output
Number Of Houses : 0
{"houses":[]}
Any help to resolve this is greatly appreciated.
From your posted code, I don't see any printing of the resultset.
How do you know it's not returning anything?
Can you put a print statement before/after the while (rs.next) cycle (an if, a counter) to see if it' s actually empty?
If it is empty, try removing table alias from your query
EDIT:
Modify the query in "select house_id from houses_tbl", execute the query and exactly after
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
put
if (rs.next()){
System.out.println("Got house!");
}else{
System.out.println("No houses here!");
}
and momentarily comment out/bypass the printing code. This is to check baseline operativity of you env in that context. If this doesn't work, must be a database/driver issue, to me

SPARQL query take a longer time in Eclipse compare to commande line

I need to compare SPARQL to SQL(Oracle based).
So I started with Jena and Eclipse. I created my RDF file and queries in SPARQL but when I execute a query in command line it took 5 secondes to get the result and with Eclipse it took 15 secondes !
The difference between the two computation times is huge and I can't compare properly these databases...
Is anyone know why ?
I save my RDF file in RDF/XML mode (by default).
Thanks !
There's the code i use :
String q = "SELECT ?appID ?appLibelle ?droit ?login ?password ?prenom ?nom "
+ "WHERE { "
+ "?empdroitapp EMPDROITAPP:EMP_ID ?emp . "
+ "?empdroitapp EMPDROITAPP:APP_ID ?app . "
+ "?empdroitapp EMPDROITAPP:EMPDroitAPP_Droit ?droit . "
+ "OPTIONAL { ?empapp EMPAPP:EMP_ID ?emp . "
+ "?empapp EMPAPP:APP_ID ?app . "
+ "?empapp EMPAPP:EMPAPP_Login ?login . "
+ "?empapp EMPAPP:EMPAPP_Password ?password . } . "
+ "?emp EMP:EMP_ID ?empID . "
+ "?emp EMP:EMP_Prenom ?prenom . "
+ "?emp EMP:EMP_Nom ?nom . "
+ "?app APP:APP_ID ?appID . "
+ "?app APP:APP_Libelle ?appLibelle . "
+ "} ORDER BY ASC(?empID)";
String prefix = "PREFIX LDAP: <http://example.com/property#>";
String prefixEMP = "PREFIX EMP: <http://example.com/property/emp#>";
String prefixAPP = "PREFIX APP: <http://example.com/property/app#>";
String prefixEMPAPP = "PREFIX EMPAPP: <http://example.com/property/empapp#>";
String prefixEMPDROITAPP = "PREFIX EMPDROITAPP: <http://example.com/property/empdroitapp#>";
String queryString = prefix + NL + prefixEMP + NL + prefixAPP + NL
+ prefixEMPAPP + NL + prefixEMPDROITAPP + q;
Query query = QueryFactory.create(queryString);
//query.serialize(new IndentedWriter(System.out, false));
QueryExecution qexec = QueryExecutionFactory.create(query, m);
long chrono = java.lang.System.currentTimeMillis();
try {
// Assumption: it's a SELECT query.
ResultSet rs = qexec.execSelect();
//String str = "appID\tappLibelle\tdroit\tlogin\tpassword\tprenom\tnom\n";
// The order of results is undefined.
for (; rs.hasNext();) {
QuerySolution rb = rs.nextSolution();
// Get title - variable names do not include the '?' (or '$')
RDFNode appID = rb.get("appID");
RDFNode appLibelle = rb.get("appLibelle");
RDFNode droit = rb.get("droit");
RDFNode login = rb.get("login");
RDFNode password = rb.get("password");
RDFNode prenom = rb.get("prenom");
RDFNode nom = rb.get("nom");
// Check the type of the result value
if (appID.isResource()) {
Resource res = (Resource) appID;
System.out.print("\t" + res);
} else {
System.out.print("\t" + appID);
}
if (appLibelle != null) {
System.out.print("\t" + appLibelle);
} else System.out.print("\tnull");
if (droit != null) {
System.out.print("\t" + droit);
} else System.out.print("\tnull");
if (login != null) {
System.out.print("\t" + login);
} else System.out.print("\tnull");
if (password != null) {
System.out.print("\t" + password);
} else System.out.print("\tnull");
if (prenom != null) {
System.out.print("\t" + prenom);
} else System.out.print("\tnull");
if (nom != null) {
System.out.print("\t" + nom);
} else System.out.print("\tnull");
System.out.println();
//str += "\n";
}
//System.out.println(str);
} finally {
// QueryExecution objects should be closed to free any system
// resources
qexec.close();
}
long tmp = java.lang.System.currentTimeMillis();
System.out.println("Temps écoulé : " + (tmp - chrono) + "ms");

How to retrieve values after calculation?

I have a method to show the values of table that satisfy the condition: show all value in table tblFuel if alarmType != 60 and nearest alarmType == 60, all of my code here:
public ArrayList<FuelData> BaoCaoDoXang(String accountID, String deviceID,
String fromTime, String toTime, String timezone)
throws DBException, SQLException {
ArrayList<FuelData> list = new ArrayList<FuelData>();
ResultSet rs = null;
DBConnection dbc = null;
Statement stmt = null;
FuelData reportFuel;
int alarmType = -1;//(1)initialize here*********************************************************1
try {
dbc = DBConnection.getDefaultConnection();
long epf = ConvertToEpoch(fromTime + " 00:00:00", timezone);
long epl = ConvertToEpoch(toTime + " 23:59:59", timezone);
String sql = "SELECT * "
+ " FROM tblFuel F INNER JOIN tblDoXang DX "
+ " ON DX.thoiGian = F.timestamp "
+ " where (F.timestamp BETWEEN " + epf + " and " + epl
+ ") " + " and F.accountID = '" + accountID
+ "' and F.deviceID = '" + deviceID
+ "' and F.alarmType = '" + alarmType//expectation value(4)*************************4
+ "' order by F.timestamp asc";
stmt = dbc.execute(sql);
rs = stmt.getResultSet();
double lastValue = 0;
int temp = -1;
while (rs.next()) {
// double fuel = rs.getDouble("nhienLieu");
temp = rs.getInt("alarmType");
if(temp != 60)
alarmType = temp;
if(temp == 60 && alarmType != -1)//(2)alarmType value after calculation*****************2
{
double currentValue = rs.getDouble("fuelLevel");
double changeValue = lastValue == 0 ? 0 : currentValue
- lastValue;
lastValue = currentValue;
reportFuel = new FuelData(rs.getString("accountID"),
rs.getString("deviceID"), rs.getInt("timestamp"),
rs.getDouble("latitude"), rs.getDouble("longitude"),
rs.getString("address"), currentValue,
rs.getDouble("odometerKM"), rs.getInt("status"),
changeValue,alarmType ,//(3)here************************************************3
rs.getDouble("nhienLieu"));
list.add(reportFuel);
/*
* if(fuel > 0){ changeValue = fuel; }
*/
}
}
} catch (SQLException sqe) {
throw new DBException("ReportByStatusCode", sqe);
} finally {
if (rs != null) {
try {
rs.close();
} catch (Throwable t) {
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Throwable t) {
}
}
DBConnection.release(dbc);
}
return list;
}
I initialized my variable(alarmType) in (1) int alarmType = -1;//(1)initialize here*********************************************************1
and then checked the given condition and calculated in (2) and got the satisfied value in (3). I expected to put value of alarmType in (3)
double lastValue = 0;
int temp = -1;
while (rs.next()) {
// double fuel = rs.getDouble("nhienLieu");
temp = rs.getInt("alarmType");
if(temp != 60)
alarmType = temp;
if(temp == 60 && alarmType != -1)//(2)alarmType value after calculation*****************2
{
double currentValue = rs.getDouble("fuelLevel");
double changeValue = lastValue == 0 ? 0 : currentValue
- lastValue;
lastValue = currentValue;
reportFuel = new FuelData(rs.getString("accountID"),
rs.getString("deviceID"), rs.getInt("timestamp"),
rs.getDouble("latitude"), rs.getDouble("longitude"),
rs.getString("address"), currentValue,
rs.getDouble("odometerKM"), rs.getInt("status"),
changeValue,alarmType ,//(3)here************************************************3
rs.getDouble("nhienLieu"));
list.add(reportFuel);
/*
* if(fuel > 0){ changeValue = fuel; }
*/
}
}
to (4) and then execute the query
String sql = "SELECT * "
+ " FROM tblFuel F INNER JOIN tblDoXang DX "
+ " ON DX.thoiGian = F.timestamp "
+ " where (F.timestamp BETWEEN " + epf + " and " + epl
+ ") " + " and F.accountID = '" + accountID
+ "' and F.deviceID = '" + deviceID
+ "' and F.alarmType = '" + alarmType//expectation value(4)*************************4
+ "' order by F.timestamp asc";
. I have checked and recognized that the value return in (3) is true, however it seemed that the value in (4)(alarmType) which got from (1)(alarmType = -1), but not from (3) so my code return the wrong result. So my question is: how to retrieve correctly value from (3) to put to (4)?(In the other word: how to get value of alarmtype in while loop to put in in SQL query?).(other way) It is very easy if I add one more column in my table to put the values that calculated in (3)(by writing a service in somewhere), but what I can do without of doing that?
Do something like
alarmType
loopingConstruct {
sql String
execute sql string to get result set (rs)
loop through rs
get alarm type value and set it to alarm type
create FuelData object
add FuelData to the list
}
Looping construct context holds the modified value of alarmType during its execution which will be used in sql String.
Assumption - Result set (rs) returned contains only one row. If this is not the case then alarmType will have its value set to the value returned by the last row in the rs.

Categories