i have 3 string list called Cname,cnamedb,Pname. These 3 lists has a result obtained by query the SQL database.cname and Pname results are getting from querying excel database. cnamedb result is getting from querying SQL database.
i declared and stored into array like this.
List Cname = new ArrayList();
List Pname =new ArrayList();
List cnamedb=new ArrayList();
Cname.add(rs.getString("Cname"));
Pname.add(rs.getString("Pname"));
cnamedb.add(res.getString("Cname"));
i tried like this
boolean hasCommonName = Cname.retainAll(Cnamedb);
if(hasCommonName){
out.println(Cname+"<br>");
out.println(hasCommonName);
}
boolean haspname=Pname.retainAll(Cnamedb);
if(haspname){
out.println(haspname);
}
This is just giving me a answer true for the first if statement but not printing the list elements. for the second if statements no results am getting.
i need to find out common elements exists in database and the excel, first i need to get common elements from Cname and Cnamedb and then from Pname and Cnamedb. how do i get the common elements.please provide me the code snippet.
the below given snippet worked for me.
List<String> commonToCnameAndCnamedb = new ArrayList<String>(Cname);
List<String> commonToPnameAndCnamedb = new ArrayList<String>(Pname);
boolean hasCommonName = commonToCnameAndCnamedb.retainAll(cnamedb);
if (hasCommonName) {
System.out.println(commonToCnameAndCnamedb + "<br>");
System.out.println(hasCommonName);
}
boolean haspname = commonToPnameAndCnamedb.retainAll(cnamedb);
if (haspname) {
System.out.println(commonToPnameAndCnamedb + "<br>");
System.out.println(haspname);
}
Related
I'm using arraylist to hold my result set data from the database. My result set contains four rows. I'm using arraylist of object type. I'm able to save my data to arraylist. But when I tried to print the data from arraylist it is printing the data from last object that is saved. But when I tried to print the arraylist as it is it is printing four different objects. Please help me in printing the arraylist data.
My Servlet:
List<FMB_BOOKS> books = FMB_BOOKS.getBooks();
System.out.println("List from Books: " + books);
PrintWriter out = response.getWriter();
Iterator<FMB_BOOKS> itr = books.iterator();
FMB_BOOKS results = new FMB_BOOKS();
out.println(books.toString());
for (FMB_BOOKS book : books)
{
System.out.println("Book ID from Books: " + book.getBookid());
out.println(book.getBookid());
out.println(book.getBookname());
out.println(book.getAuthorname());
out.println(book.getCategory());
out.println(book.getLanguage());
out.println(book.getYear());
out.println(book.getPublisher());
out.println(book.getCaption());
out.println(book.getImage());
}
My Java Class:
while (rs.next())
{
FMB_BOOKS Obj_Books = new FMB_BOOKS();
System.out.println("Inside While Result Set");
FMB_BOOKS.setBookid(rs.getString("BOOK_ID"));
FMB_BOOKS.setBookname(rs.getString("BOOK_NAME"));
FMB_BOOKS.setAuthorname(rs.getString("AUTHOR_NAME"));
FMB_BOOKS.setCaption(rs.getString("CAPTION"));
FMB_BOOKS.setCategory(rs.getString("CATEGORY"));
FMB_BOOKS.setYear(rs.getString("PUBLISHED_YEAR"));
FMB_BOOKS.setPublisher(rs.getString("PUBLISHER"));
FMB_BOOKS.setLanguage(rs.getString("LANGUAGE"));
FMB_BOOKS.setImage(rs.getString("IMAGE"));
books.add(Obj_Books);
}
I have a stored procedure in mysql that returns more than one lines.
My java code to execute it is:
preparedStmt = conn.prepareCall(queryString);
preparedStmt.setString(1, String.valueOf(patient_id));
//System.out.print("select patient data java file 1 ");
boolean results = preparedStmt.execute();
int rowsAffected = 0;
// Protects against lack of SET NOCOUNT in stored procedure
while (results || rowsAffected != -1) {
if (results) {
rs = preparedStmt.getResultSet();
break;
} else {
rowsAffected = preparedStmt.getUpdateCount();
}
results = preparedStmt.getMoreResults();
}
int i = 0;
obj = new JSONObject();
while (rs.next()) {
JSONArray alist = new JSONArray();
alist.put(rs.getString("patient_id"));
alist.put(rs.getString("allergy"));
alist.put(rs.getString("allergy_description"));
alist.put(rs.getString("allergy_onset_date"));
alist.put(rs.getString("agent_description"));
alist.put(rs.getString("agent"));
alist.put(rs.getString("severity"));
obj.put("ps_allergies", alist);
i++;
}
conn.close();
At the end, ps_allergies json object contains only the last line of the query. This is the print output:
["1","week",null,"2017-07-07","vacation home","test2","mobile contact"]
I want ps_allergies to contain something similar to
[["1","hydrogen peroxide","Nuts","2017-07-04","Nursing profressionals","43","Paramedical practinioners"],["1","week",null,"2017-07-07","vacation home","test2","mobile contact"]...]
Do you know how to fix this?
Not exactly knowing what library you use, but it might have something to do with this line:
obj.put("ps_allergies", alist);
A put method in general associates the specified value with the specified key in a map. Since you are constantly overwriting you key 'ps_allergies' in the loop it will only retain the last value.
You might want to associate a list/array to ps_allergies and you then add every alist object in this list/array.
I found the solution. Instead of put I'm using append method.
obj.append("ps_allergies", alist);
The resulted output now is:
[["1","hydrogen peroxide","Nuts","2017-07-04","Nursing professionals","43","Paramedical practitioners"],["1","chlorhexidine","test123","2017-07-15","mobile contact","test232","pager"],["1","Resistance to unspecified antibiotic","Feb3","2017-03-02","mobile contact","test232","pager"],["1","week",null,"2017-07-07","vacation home","test2","mobile contact"]]
I have some data in SQLite database, which I would like to show in a List based on small logic.
I have three fields in my table,
first field : id
second field : title
third field : type
where Type can be : Monthly or Yearly
Here is my code:
// Generate real data for each item
public List<ReminderItem> generateData(int count) {
ArrayList<ReminderItem> items = new ArrayList<>();
// Get all reminders from the database
List<Reminder> reminders = rb.getAllReminders();
// Initialize lists
List<String> Titles = new ArrayList<>();
List<String> Type = new ArrayList<>();
List<Integer> IDList= new ArrayList<>();
// Add details of all reminders in their respective lists
for (Reminder r : reminders) {
Titles.add(r.getTitle());
Type.add(r.getType());
IDList.add(r.getID());
}
return items;
}
This is the situation, where I need help from you guys, As you can see still, I am showing each and every record from database to list, no matter from which Type it belongs.
Now, I just want to show records in a List, which belongs to Type "Monthly" only
So exactly what I have to do ? How can I show records in a List for the Type of "Monthly" only
I have a String variable namely, strType = "Monthly";
You have two option to do this.
First is directly get only those record from database which reminder type is "Monthly" by execute below sql statement.
SELECT id,title,type FROM table_name WHERE type = "Monthly"
Second is check reminder type is equal to "Monthly" when you add data into List.
for (Reminder r : reminders) {
String reminderType = r.getType();
if(reminderType.equalsIgnoreCase(strType)) {
Titles.add(r.getTitle());
Type.add(reminderType);
IDList.add(r.getID());
}
}
Full Code
// Generate real data for each item
public List<ReminderItem> generateData(int count) {
String strType = "Monthly";
ArrayList<ReminderItem> items = new ArrayList<>();
// Get all reminders from the database
List<Reminder> reminders = rb.getAllReminders();
// Initialize lists
List<String> Titles = new ArrayList<>();
List<String> Type = new ArrayList<>();
List<Integer> IDList= new ArrayList<>();
// Add details of all reminders which type="Monthly" in their respective lists
for (Reminder r : reminders) {
String reminderType = r.getType();
if(reminderType.equalsIgnoreCase(strType)) {
Titles.add(r.getTitle());
Type.add(reminderType);
IDList.add(r.getID());
}
}
return items;
}
When you select from your sqlite db you can add filter there
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_A + " WHERE " +
COLUMN_TYPE + "=?", new String[]{ arg0 }); // arg0 = "Monthly"
This will increase your performance instead of filtering List after load
<%
st = con.createStatement();
rs = st.executeQuery("select pf_nm from portfolio");
while(rs.next())
{
out.print(rs.getString(1)); //divide the result into multiple values
}
%>
The result in above code may vary according to data fetched. Example of result is as below:
Google Facebook
or
Google
or
Google Facebook Apple
If I understood your question and comment correctly then you can do something like this
ArrayList<String> cols = new ArrayList<String>();
while(rs.next())
{
cols.add(rs.getString(1));
// Do something..
}
Edit : What I understood from your previous question
String result = rs.getString(1); // gives "Google Facebook Apple AT&T" as result
String[] names = result.split("\\s"); // Split the line by whitespace
If you want you can also make use of ArrayList. You can also use hashMap if you required key values assoiciation (I am not sure thats what you want). Following are some useful links
1. Splitting string in java
2. How to use ArrayList in Java
3. HashMap example in Java
Here is complete pseudo code for you.
public class StringSplit {
public static void main(String [] sm){
String str = "Google Facebook Apple AT&T";
// If you have more than one whitespace then better use \\s+
String[] names = str.split("\\s");
for(int i =0; i<names.length; i++){
System.out.println(i +" : " + names[i]);
}
}
}
I hope this helps you.
I have 2 input dates: myStartDate,myEndDate and a table TEST_TABLE with columns
TEST_ID, TEST_USER,TEST_START, TEST_END
I need to check if the range of dates between myStartDate and myEndDate have corresponding records in the TEST_TABLE.
I also need to ensure that I don't retrieve duplicate records.
Here's a sample of the logic I have so far:
Assuming,
myStartDate=06/06/2012;myEndDate=06/09/2012
int diff = myEndDate - myStartDate; //In this case = 3
String myQuery = "SELECT * FROM TEST_TABLE WHERE"+ myStartDate +"BETWEEN TEST_START AND TEST_END OR "+ (myStartDate +1) +" BETWEEN TEST_START AND TEST_END OR"+ (myStartDate+2)+"BETWEEN TEST_START AND TEST_END OR"+(myStartDate+3)+"BETWEEN TEST_START AND TEST_END";
List <TestTableData> myList = new List();
//Exceute query & save results into myList using add method
Want to know if there's any way to test the range of dates between myStartDate &myEndDate using a for loop in java code, instead of the approach used above in myQuery.Also, how can I avoid duplicates.
New to Java so any help would be appreciated!
Use a ResultSet to iterate over the output, like the code below.
while (res.next()) {
String col1= res.getString("col1");
String col2 = res.getString("col2");
}
If you use an Array implementation , it does not allow for duplicate elements and hence there is no need to check for one.
But if you must use a list then , you could use the following code to remove any duplicate elements.
public static void removeDuplicates(List list)
{
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = list.iterator(); iter.hasNext(); ) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
list.addAll(newList);
}
I think what you are asking are some generic questions about how to read a database and how to handle dates in java. I will give you some sample code below. But I suggest you look at the java database tutorial http://docs.oracle.com/javase/tutorial/jdbc/index.html and the java.util.Date api doc http://docs.oracle.com/javase/1.5.0/docs/api/java/sql/Date.html for more info.
Here is some sample code that specifically demonstrates how to implement your question:
// get the input dates
// they are hard coded in this example
// but would probably normally be passed in
String startDateStr = "2/3/03";
String endDateStr = "3/1/03";
// unfortunately, there are 2 "Date" classes in this code and you need to differentiate
// java.util.Date is the standard java class for manipulating dates
// java.sql.Date is used to handle dates in the database
// name conflicts like this are rare in Java
SimpleDateFormat dateFmt = new SimpleDateFormat("M/d/yy");
java.util.Date myStartDate = dateFmt.parse(startDateStr);
java.util.Date myEndDate = dateFmt.parse(endDateStr);
// conneect to the database
// I am using mysql and its driver class is "com.mysql.jdbc.Driver"
// if using a different database, you would use its driver instead
// make sure the jar containing the driver is in your classpath (library list)
// you also have to know the url string that connects to your database
Class.forName("com.mysql.jdbc.Driver").newInstance(); // loads the driver
Connection dbConn = DriverManager.getConnection(
"jdbc:mysql://localhost/testdb", "(db user)", "(db password)"
);
// get the database rows from the db table
// my table is named "testtable"
// my columns are named "DateStart" and "DateEnd"
Statement st = dbConn.createStatement();
String sqlStr = "Select * from testtable";
ResultSet rs = st.executeQuery(sqlStr);
// loop through the rows until you find a row with the right date range
boolean foundRange = false;
while (rs.next()) {
java.util.Date dbStartDate = rs.getDate("DateStart");
java.util.Date dbEndDate = rs.getDate("DateEnd");
if (myStartDate.before(dbStartDate)) continue;
if (myEndDate.after(dbEndDate)) continue;
foundRange = true;
break;
}
if (foundRange) {
// code that executes when range is found in db
} else {
// code that executes if range not found in db
}
dbConn.close();
Hope this helps you get started.