Using Java variables with Sikuli in Selenium-Webdriver - java

The code below is a Java code in Selenium Webdriver. The code reads a long list from an excel sheet. It stores the values in each excel cell in variables, LastName and FirstName. I need to use the variables in a query, after navigating to SQL Server management studio database. This is where am having issues. when I use the command 'screen.type(LastName);', the variable LastName throws "cannot be resolved to a variable" error.
How do I use the variables LastName and FirstName defined in Java in Sikuli.
File src = new File ("C:\\EmployeeList.xlsx");
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet1 = wb.getSheetAt(0);
int rowcount=sheet1.getLastRowNum();
System.out.println("Total Row is :" + rowcount);
for (int i=0; i<rowcount;i++) {
String LastName=sheet1.getRow(i).getCell(0).getStringCellValue();
String FirstName=sheet1.getRow(i).getCell(1).getStringCellValue();
System.out.println("Data Employee List is " +i+ " "+"is "+ LastName+ ", "+FirstName+");
}
wb.close();
//Navigated into SQL Server management studio database
screen.type(LastName);

LastName is declared in the for loop local scope, so it doesn't exist outside the for. You need to declare it outside
String lastName, firstName;
for (int i = 0 ; i < rowcount ; i++) {
lastName = sheet1.getRow(i).getCell(0).getStringCellValue();
firstName = sheet1.getRow(i).getCell(1).getStringCellValue();
System.out.println("Data Employee List is " + i + " " + "is " + lastName + ", " + firstName);
}
screen.type(lastName);
I'm not sure if this on purpose, but screen.type(lastName); will use only the last value of lastName. If you want to use all of them insert it into the loop. In that case you can leave the lastName declaration inside the for
for (int i = 0 ; i < rowcount ; i++) {
String lastName = sheet1.getRow(i).getCell(0).getStringCellValue();
String firstName = sheet1.getRow(i).getCell(1).getStringCellValue();
System.out.println("Data Employee List is " + i + " " + "is " + lastName + ", " + firstName);
screen.type(lastName);
}
By the way, variables in Java should start with lower case.

Related

storing values with .nextLine() in array skipping lines

My previous question was closed, but the answer suggested wasn't much help to me. Sorry for the inconvenience.
I'm trying to store fname, lname, address, city, state, and zip in array customerData[30][6]. However, it seems to be skipping lines where I'd input the information.
Code
public void addCustomer() throws IOException {
Scanner scan = new Scanner(System.in);
int numCustomers = 0;
String[][] customerData = new String[30][7];
System.out.println("how many customers");
numCustomers = scan.nextInt();
BufferedWriter writer = new BufferedWriter(
new FileWriter("/Users/simonshamoon/eclipse-workspace/Final Project/src/customerdata.txt"));
BufferedWriter loginWriter = new BufferedWriter(
new FileWriter("/Users/simonshamoon/eclipse-workspace/Final Project/src/userlogin.txt"));
for (int i = 0; i < numCustomers; i++) {
System.out.println("enter customer data (fname, lname, address, city, state, zip)");
for (int j = 0; j < customerData[i].length; j++) {
customerData[i][j] = scan.nextLine();
}
writer.write(customerData[i][0] + ", " + customerData[i][1] + ", " + customerData[i][2] + ", "
+ customerData[i][3] + ", " + customerData[i][4] + ", " + customerData[i][5] + "\n");
loginWriter.write(customerData[i][0].charAt(0) + customerData[i][1] + ", " + rand.nextInt(10001) + "ASU"
+ ", Customer" + "\n");
}
writer.flush();
writer.close();
loginWriter.flush();
loginWriter.close();
}
Output
how many customers
1
enter customer data (fname, lname, address, city, state, zip)
fname
lname
123 address dr
city
state
zip
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
at java.base/java.lang.String.charAt(String.java:709)
at Employee.addCustomer(Employee.java:156)
at Employee.displayEmployeeMenu(Employee.java:196)
at BasicMethods.promptUser(BasicMethods.java:48)
at Shop.main(Shop.java:8)
I want it so that customerData[i][0] = fname, customerData[i][1] = lname, etc etc. I've tried playing around with .nextLine and the array sizes, but I believe the problem stems from the space needed in address.
So here you create the customer data:
for (int j = 0; j < customerData[i].length; j++) {
customerData[i][j] = scan.nextLine();
}
And here is the writer code using charAt:
loginWriter.write(customerData[i][0].charAt(0) + customerData[i][1] + ", " + rand.nextInt(10001) + "ASU" + ", Customer" + "\n");
So it looks like customerData[i][0] is an empty String since it's the only use of charAt which throws the index exception.
I suggest you either output your individual data items or better yet, step through your code with a debugger.
Since you don't show the surrounding code (how is scan created; maybe it's reused but accidentally closed in the meantime?) we can only make reasonable guesses.

Java resultSet getInt() returns no value

Here, resultSet.getInt() doesn't work, but I do not know what is wrong with my code.
I want to increment the value of the column (with the name as the variable 'attendance'). Using the SELECT statement I want to read the current value and by using UPDATE I want to increment the corresponding value by 1. But the problem is that int a = r.getInt("'" + attendance + "'"); doesn't work. It always returns the value 0 although the current value isn't 0 (e.g. 1). What is wrong with my code?
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:"+ x +".db");
s = c.createStatement();
r = s.executeQuery("SELECT '" + attendance + "' FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'");
while (r.next()){
int a = r.getInt("'" + attendance + "'");
int b = 1 + a;
String sql = "UPDATE viewer SET '" + attendance + "' = ? WHERE name = ? AND year = ? ";
p = c.prepareStatement(sql);
p.setInt (1,b);
p.setString (2,name);
p.setInt (3,year);
p.executeUpdate();
}
p.close();
c.close();
// r.getInt() value always 0
}
catch (ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
Since you wrap the name of the column in single quotes, it is considered as the string literal 'attendance' and not the name of the column which is the value of the variable attendance.
Change to:
"SELECT " + attendance + " FROM viewer WHERE name = '" + name + "' AND year = '" + year + "'"
(why do you concatenate the arguments name and year? Use placeholders ? just like the UPDATE statement)
and
"UPDATE viewer SET " + attendance + " = ? WHERE name = ? AND year = ? "
and
int a = r.getInt(attendance);
since you only have 1 column, you can use column index, instead of column names
int a = r.getInt(0);

resultset.next() is showing output of first row only

So, I have something like this:
System.out.println("Enter owner's IC no. or plate no. : ");
String update = in.nextLine();
String sql = String.format("SELECT * FROM `vehicle` WHERE ic='%s' OR plate ='%s'",update,update);
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
System.out.println("IC and PLate No. not found....");}
while (rs.next()) {
regno = rs.getInt("regno");
name = rs.getString("name");
ic = rs.getString("ic");
plate = rs.getString("plate");
color = rs.getString("color");
year = rs.getInt("year");
make = rs.getString("make");
model = rs.getString("model");
capacity = rs.getDouble("capacity");
type = rs.getString("type");
maxload = rs.getDouble("maxload");
System.out.println(toString());
}
What I'm trying to do is, if data is found in the database, it will then print the following table for outputs that match.
Now, It is supposed to print out every output. But, it only prints out the first one.
I believe that the following code is the cause:
if(rs.next()) {
System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
System.out.println("IC and PLate No. not found....");}
I also faced the same problem, when used select query with Prepared statement.
For example-
String sqlquerySELECTAgentsWithParam = " select * from AGENTS WHERE AGENT_CODE = ( ? ) ";
it returned a single row, since I've used IF condition and then while(rs.next())
I couldn't print the single row, Hence, I've used do-while loop like below in order to print the first-row result. code snippet below- hope it will help !!
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(oracelDBUrl, oracleDBUser,oracleDBPwd );
if (conn != null) { System.out.println("Connected to the Oracle DB "); }
else { System.out.println("Failed to Connect to Oracle DB "); }
PreparedStatement pstmt = conn.prepareStatement(sqlquerySELECTAgentsWithParam);
pstmt.setString(1,"<agent_id>");
ResultSet rs = pstmt.executeQuery();
boolean returnResultrs = rs.next();
System.out.println("Fetched Result is = " +returnResultrs);
if(returnResultrs)
{
do {
System.out.println("Inside Do - While Loop");
System.out.println("AGENT_CODE = " + rs.getString(1)+ "has AGENT_NAME = " +rs.getString(2));
}
while(rs.next());
}
Use MessageFormat to format the output, and the counter to determine if empty result set, like so:
String strFormat = "RegNo. {0}\tName {1}\tIC {2}\tPlate No. {3}\tColor {4}\tYear {5}\tMake {6}\tModel {7}\tCapacity {8}\tType {9}\tMax Load {10}");
int counter = 0;
while (rs.next()) {
counter++;
regno = rs.getInt("regno");
name = rs.getString("name");
ic = rs.getString("ic");
plate = rs.getString("plate");
color = rs.getString("color");
year = rs.getInt("year");
make = rs.getString("make");
model = rs.getString("model");
capacity = rs.getDouble("capacity");
type = rs.getString("type");
maxload = rs.getDouble("maxload");
System.out.println(MessageFormat.format(strFormat, regno, name, ic, plate, color, year, make, model, capacity, type, maxload));
}
if (counter == 0) {
System.out.println("IC and PLate No. not found....");
}
So I see two issues here. The biggest one is this:
System.out.println(toString());
That calls the .toString() method on the current class, which will not output any of the data from your ResultSet. At least, not based on any of the code you've shown. You're storing all of the values coming back from the ResultSet in variables, but those variables don't appear to be getting used anywhere. You need to get those variables to your .println() somehow.
The second issue is that rs.next() moves the cursor forward one row. So when you do this:
if(rs.next()) {
That causes you to skip the first row. This is actually kind of tricky to fix, because there's no good way to tell whether or not a ResultSet is empty without calling .next(). The way I'd probably handle this is to pull all of the results into objects in a list, and then do all the printing based on the list, and not on the ResultSet itself.

Java - how to insert data into data base from txt file

I am wondering how to read in a file and insert into a table in my data base. I written this:
String customerFile = "customer.txt";
Connection myConnect = ....
Statement mySt = myConnect.createStatement();
mySt.executeUpdate(..create customer table..);
int SSN;
String CNAME;
String GENDER;
int AGE;
String PROFESSION;
String line;
String[] tokens;
FileReader file1 = new FileReader(customerFile);
BufferedReader buffer1 = new BufferedReader(file1);
//throw away first line
line = buffer1.readLine();
//continue with rest of file
while((line = buffer1.readLine()) != null)
{
tokens = line.split(",");
SSN = Integer.parseInt(tokens[0]);
CNAME = tokens[1];
GENDER = tokens[2];
AGE = Integer.parseInt(tokens[3]);
PROFESSION = tokens[4];
String insertString = "insert into customer values ( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +")";
mySt.executeUpdate(insertString);
}
I thought this was the right way to insert into a table. However, the issue I am having with is that the variables aren't being read in the right way.
Example rows:
3648993,Emily,male,63,Consulting
5022334,Barbara,male,26,Finance
With the example above, I would want to have a table with 2 rows and 5 columns but the code I put on top gave me an error when it reaches the name. I am not sure where the issue is.
You should replace insertString with
myConnect = getConnection();
myConnect.setAutoCommit(false);
File file = new File(fileName);
fis = new FileInputStream(file);
pstmt = myConnect.prepareStatement("insert into customer( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +") values (?,?,?,?,?)");
pstmt.setString(1, SSN);
pstmt.setString(2, AGE);
....
pstmt.executeUpdate();
myConnect.commit();
Source : Insert text file into MySQL
Make sure you put quotes around string fields, so instead of:
String insertString = "insert into customer values ( " + SSN + ", " + CNAME + "," +
GENDER + ", " + AGE + ", " + PROFESSION +")";
do:
String insertString = "insert into customer values ( " + SSN + ", '" + CNAME + "','" +
GENDER + "', " + AGE + ", '" + PROFESSION +"')";
Normally I do such things in two steps:
1) create a java class representing just one row of the textfile. This class is instantiated with a line from the txt-file and this single row is parsed and the fields are created, so I have for every single field a getter and a setter having the right fieldtype. within this class I'm able to perform tests and corrective actions if a field is wrong or even empty.
2) I create a Writer-class that reads the textfile line by line and writes every single line into the db, mostly starting with the second line, because the first line contains the header. I strictly use PreparedStatement and use batchwriting, at the end, when file looping is finished, write the batch to the DB with PreparedStatement.executeBatch() and then I close down all DB-objects.

CSV reading in java

Im having trouble reading from a CSV file
final String DELIMITER = ",";
Scanner fileScan = null;
Scanner dataSetScan = null;
String dataSet = null;
String sql = "";
File users = new File("user.txt");
String nickname = "";
String lastname = "";
String firstname = "";
String cartype = "";
String personimage = "";
String carimage = "";
int user_id = 0;
try {
fileScan = new Scanner(users);
} catch (Exception e) {
System.out.println(e);
}
while(fileScan.hasNext()){
dataSet = fileScan.nextLine();
dataSetScan = new Scanner(dataSet);
dataSetScan.useDelimiter(DELIMITER);
nickname = dataSetScan.next();
lastname = dataSetScan.next();
firstname = dataSetScan.next();
cartype = dataSetScan.next();
personimage = dataSetScan.next();
carimage = dataSetScan.next();
sql += "INSERT INTO users VALUES (";
sql += user_id++ + ", ";
sql += "'" + nickname + "', ";
sql += "'" + lastname + "', ";
sql += "'" + firstname + "', ";
sql += "'" + cartype + "', ";
sql += "'" + personimage + "', ";
sql += "'" + carimage + "' ";
sql += ");\n";
}
The above code wont work on the example file
alice,Wonder-Land,Alice,red Vauxhall Corsa,alice.jpg,alice_car.jpg
bob,Kett,Robert,,,
charlie,Carlos,Don,,,
However, it works just fine when there is a comma at the end of the line. (hvaing a comma here is not an option)
What can i do to make this work? It must be to do with my delimeter i think
Thank you
I wouldn't recommend using your own parser for CSV. CSV is surprisingly complex with little gotchas everywhere.
For instance, in CSV, it is legal to quote a column value with a comma in it
3 columns in this file
abc,"value1,value2",def
I recommend this library for java, it's very easy to use.
http://opencsv.sourceforge.net/
EDIT - May 2013
Since writing this post, I have switched to this library, which supports the CSV "standard" better and is actively developed.
http://supercsv.sourceforge.net/
Are you getting a NoSuchElementException from the following line?
carimage = dataSetScan.next();
If so you just need to wrap that with a hasNext check and perform a null check when you build your string.
if(dataSetScanner.hasNext()){
carimage = dataSetScan.next();
}
else{
carimage = null;
}
...
sql += carimage == null ? "NULL" : "'" + carimage + "' ";
I would recommend testing each token before inserting it,
But to answer your question, add an if condition before the last dataSetScan.next() call like so:
if (dataSetScan.hasNext()){
carimage = dataSetScan.next();
}

Categories