Inserting multiple values in one row - java

I need to insert data from my parsed XML file to mySQL table. Problem is that I have few attributes and don't know how to insert them in one row. I tried with updateString but it writes only last attribute.
Here is example from XML file:
<Tr rn=\"999999999999999\" vr=\"T\" sSpre=\"S\" reg=\"P\" dSpre=\"2010-09-30\" dOdprt=\"2000-01-01\" iban=\"SI56\" eno=\"R\" vir=\"R\" maticnaPps=\"00000000\"><Imetnik davcna=\"0000000\" matSub=\"0000000\" drz=\"705\"><PopolnoIme>xxx</PopolnoIme><KratkoIme>xxx</KratkoIme><Naslov sifTipNaslova=\"01\" sifObcina=\"039\" sifPosta=\"1303\" sifUlica=\"0000\" sifNaselje=\"059\" stHisna=\"027\" sifHsmid=\"11694551\"><Obcina>xxx</Obcina><Posta>xxx</Posta><Ulica>xxx</Ulica><Naselje>xxx</Naselje></Naslov></Imetnik></Tr>
This is scratch from my java program that I used for writing in mySQL table.
if (myWorkLine.substring(0,4).equals(Tr)) {
uprs.afterLast();
uprs.moveToInsertRow();
if (myWorkLine.contains(Tr)) {
myWorkLine = myWorkLine.substring(myWorkLine.indexOf(Tr)+4);
while (!myWorkLine.substring(0,1).equals("<")) {
myTag = myWorkLine.substring(0,myWorkLine.indexOf("="));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("=")+2);
myValue = myWorkLine.substring(0,myWorkLine.indexOf("\""));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("\"")+2);
uprs.updateString("Tr",myTag + " " + myValue);
if (myWorkLine.substring(0,myWorkLine.indexOf("\">")).indexOf(">") > 0)
break;
}
}
So once again, I need that in MySQL table column Tr contains attributes rn value, vr value, sSpre value,...
Thanks in advance.
P.S.: Please don't ask why I'm parsing XML file by this method, I had to do it that way. :)

Your code will repeatedly replace the "Tr" column with your concatenation of tag + " " + value so it'll only be the last one that goes in. Don't you perhaps want the different tags to go in different columns? Or maybe you need to continue concatenating and only call updateString at the end.
Could you post the desired table row for the given XML? That should help in determining what you are trying to achieve.
For example, if you just want to append them:
StringBuffer tr = new StringBuffer();
while (!myWorkLine.substring(0,1).equals("<")) {
myTag = myWorkLine.substring(0,myWorkLine.indexOf("="));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("=")+2);
myValue = myWorkLine.substring(0,myWorkLine.indexOf("\""));
myWorkLine = myWorkLine.substring(myWorkLine.indexOf("\"")+2);
tr.append(myTag + " " + myValue).append(",");
if (myWorkLine.substring(0,myWorkLine.indexOf("\">")).indexOf(">") > 0)
break;
}
if (tr.length() > 0) {
tr.deleteCharAt(tr.length()-1); // get rid of last comma
}
uprs.updateString("Tr",tr.toString());

Related

How do I print out information with CSV spreadsheet?

I'm currently working on a project with CSV. In the task, I am supposed to type a country name in the tester method, and when I call the tester method, it will print the information of the country. For example, "Germany Chemical 32000." However, no matter what country name I put(I'm sure that country exists in the spreadsheet), it always prints out "NOT FOUND," which I don't understand how. I'm guessing the problem is in the if statement of the countryInfo method. However, I can't find the problem probably due to a lack of domain knowledge, so I hope someone can inform me or give me a hint.
public void tester(){
FileResource fr = new FileResource();
CSVParser parser = fr.getCSVParser();
String GermanyInfo = countryInfo(parser,"Peru");
System.out.println(GermanyInfo);
}
public String countryInfo(CSVParser parser, String country){
String countryInfo = " ";
for (CSVRecord record : parser){
String nation = record.get("Country");
if (nation.contains(country)){
String countryExport = record.get("Exports");
String exportValue = record.get("Value (dollars)");
countryInfo = country + ": " + countryExport + " " + exportValue;
}else{
countryInfo = "NOT FOUND";
}
}
return countryInfo;
}
Debug Process:
Hey guys, after more testing and trying, I found out the problem is really part of the if statement. My for-each loop is running through the parser, one row at a time. The way I have this written, my if statement is checking to see whether that row contains any matching country name in the Country column, but once it finds it, it just keeps going and doesn't stop because I haven't told it to do so. It would find Germany but then move on to the next rows and bypass it until the end of the file, where it will return "not found." In order for me to fix this, I need to have a return statement following the exportValues = record.get line instead of the end of my method, OR simply type in a line that says "break;" after the money line, which will end the loop and then go to the return statement at the bottom.
If you're sure that the country search in your loop works fine, just add the return statement in the right place. I would suggest to change your method like this:
public String countryInfo(CSVParser parser, String country) {
for (CSVRecord record : parser) {
String nation = record.get("Country");
if (nation.contains(country)) {
String countryExport = record.get("Exports");
String exportValue = record.get("Value (dollars)");
return country + ": " + countryExport + " " + exportValue;
}
}
return "NOT FOUND";
}
In this case - as soon as the country is found - the method will return information about it. If no country is found - the method will return String "NOT FOUND"

jpa containing query with list

I have a table Called Media that has a column "tagList" of type List. I want to search media based on list of input tag.
I need a method like this.
List<Media> findByTagListContaining(<List> inputTagList);
This gives error but
List<Media> findByTagListContaining(String inputTag);
works fine. How to make first one works. I need partial matching as well for example if any row has tagList ["mentos","bollywood","comedy"]
and inputTagList is ["men","boll"] that row should come in result.
Hello, You can try this.
{
List<String> inputTagList = new ArrayList<String>();
inputTagList.add("men");
inputTagList.add("boll");
findByTagListContaining(inputTagList);
}
call your find By Tag List method
List<Media> findByTagListContaining(List<String> inputTagList){
String inputTagString = "[";
for(String strTemp : inputTagList){
//here create you own pattern matching code. Ex:
inputTagString+= "'" + strTemp + "%'" + ",";
}
inputTagString+="%]";
//And your inputTagString is ready to match you element ["mentos","bollywood","comedy"]
}

Web Element Groovy isSelected() and selected getting wrong result

Scenario
I want to collect all the selected [checkbox - checked] records in a table. Below is my method,
def getAlltheSelectedRecordId(String tableName){
WebDriver driver = DriverFactory.getWebDriver()
WebElement RefTable = driver.findElement(By.xpath("//*[#id='${tableName}']/tbody"))
List<WebElement> RowsOf_RefTable = RefTable.findElements(By.tagName('tr'))
int Totalcount = RowsOf_RefTable.size()
for (int row : (1..Totalcount)) {
boolean isChecked = driver.findElement(By.xpath("//*[#id='${tableName}']/tbody/tr[' + row + ']/td[2]/input")).isSelected()
println isChecked
boolean isChecked1 = driver.findElement(By.xpath("//*[#id='${tableName}']/tbody/tr[' + row + ']/td[2]/input")).selected
println isChecked1
if(isChecked){
String selectedRecordID = driver.findElement(By.xpath("//*[#id='${tableName}']/tbody/tr[' + row + ']/td[5]/a")).getText()
println selectedRecordID
}
}
}
Passing the table name as parameter and collect all the selected records in the table. But unfortunately always isChecked and isChecked1 return false
Please guide me where is the problem
The problem lies in the way, the strings are put together and the problem is already visible with the syntax highlighting here in SO:
By.xpath("//*[#id='${tableName}']/tbody/tr[' + row + ']/td[2]/input")
"...' + row + '..." does not put the value of row inside the string -- only this exact "code".
The solution is to use the proper quotes to end the string:
By.xpath("//*[#id='${tableName}']/tbody/tr[" + row + "]/td[2]/input")
Or even better, stick to the scheme already started in the beginning of the string: use Groovys string replacment:
By.xpath("//*[#id='${tableName}']/tbody/tr[${row}]/td[2]/input")

How can I check if a string is available in a table?

Here's the table (tblemployees)
How can I convert my code that used text files to a code that will use database (tables).
int intcurrentLine = -1;
String[] strLineSplit = (sb.toString()).split("\\r?\\n"); // converts sb to string then splits it by line
int intNumElements = strLineSplit.length; // number of elements
while (intcurrentLine != (intNumElements - 1)) {
intcurrentLine++;
String[] strWords = (strLineSplit[intcurrentLine]).split(" ", 2); // splits the current line by the first instance(space)
if (strEmpID.equals(strWords[0])) { // checks if the employee ID is available
JOptionPane.showMessageDialog(null, "Welcome " + strWords[1] + ", you have successfully logged in.");
strCheck = 1; // to confirm and go to time in and out process
break;
}
if ((intcurrentLine + 1) == intNumElements) { // condition to state that ID cant be found from the employee list
JOptionPane.showMessageDialog(null, "No such employee, please check the ID No. that you entered.");
}
}
Now I would like to search a column if it contains an Employee number. How do I put it to a condition, I've been searching but unable to find a clear answer. They only put how to search like this
String queryCheck = "SELECT * from messages WHERE EmpIDNo = 'COMSCI0001'";
ResultSet res = st.executeQuery(queryCheck);
then I'm lost, how to make a condition where if the employee no. doesn't exists something would happen else something would happen. I'm just confuse how to make a condition for that.
You can do like this:
String queryCheck = "SELECT * FROM messages WHERE EmpIDNo = 'COMSCI0001' LIMIT 1";
ResultSet res = st.executeQuery(queryCheck);
boolean exists = res.next();
The boolean variable exists will indicate whether a matching record exists or not.
Notice that I added LIMIT 1 at the end of the SQL as an optimization to avoid fetching more data than you really need.

After extracting data from html using a for loop, how do I insert one by one into a database?

I have extracted multiple data from an HTML using Jsoup and now I am trying to insert one by one into a derby db using JDBC on netbeans.
Here is my code:
public String nameOf() {
String nameStr = null;
String nameResults = "";
for(int j=100;j<=110;j++) {
refNum = j;
//System.out.println("Reference Number: " + refNum);
try {
//crawl and parse HTML from definition and causes page
Document docDandC = Jsoup.connect("http://www.abcd.edu/encylopedia/article/000" + refNum + ".htm").get();
// scrape name data
Elements name = docDandC.select("title");
nameStr = name.get(0).text();
//System.out.println(nameStr);
nameResults += nameStr + " ";
} catch (Exception e) {
//System.out.println("Reference number " + refNum + " does not exist.");
}
}
return nameResults;
So this method takes the names of diseases from 10 different HTMLs. What I am trying to do is to insert one name at a time to a derby db that I have created using JDBC. I have everything set up and all I have left to do is to insert each name in the corresponding name field of a table named DISEASE (which has fields: id, name, etc).
nameResults += nameStr + " ";
This part worries me as well since some diseases can have multiple words. Maybe I should use a list of some sort?
Please help! Thanks in advance.
Something like:
public List<String> nameOf() {
...
List<String> nameResults = new ArrayList<String>();
...
nameResults.add(nameStr);
...
return nameResults;

Categories