Iterate over a result set with an iterator ? - java

I got a result set "rs" from a database. rs contains only one column. I want to access the row at by its index and not all rows. Right now, i know that I can use this to iterate -
while(rs.next()){
rs.getString("employee_name")
}
But, it does not let me select the row.
Actually, I want to take a row, add a comma to it and then add the next row. There is no comma after the last element. So, I will need to iterate up to second last or n-1 th row and keep on adding commas. After that, i only need to append the last row to my string and the job is done.

Try the next:
Set<String> set = new LinkedHashSet<String>();
while(rs.next()) {
set.add(rs.getString("employee_name"));
}
Iterator<String> it = set.iterator();
StringBuilder sb = new StringBuilder();
while(it.hasNext()) {
sb.append(it.next());
if (it.hasNext()) {
sb.append(",");
}
}
String result = sb.toString();

String temp = "";
StringBuilder sb = new StringBuiler();
while(rs.next()){
sb.append(rs.getString("employee_name"));
sb.append(",");
}
temp = sb.toString();
temp = temp.substring(0, temp.length()-1);

Related

how to get arraylist values one by one and put it in stringbuilder java?

all,
I have an arraylist and I want to take the values one by one and put them in the string builder.
I have tried several steps, such as looping for and foreach
this is my code :
try{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/"+jComboBox1.getSelectedItem()+"","root","");
Statement stmt=con.createStatement();
for(int i =0; i < box.size();i++){
if(box.get(i).isSelected()){
//System.out.print(box.get(i).getText().trim());
ResultSet rs=stmt.executeQuery("select "+box.get(i).getText().trim()+" from "+jComboBox3.getSelectedItem()+";");
while(rs.next()){
isikolom = rs.getString(1);
isi.add(isikolom);
String getkey = jTextField1.getText().toString();
byte[] key = getkey.getBytes();
RC4 rc = new RC4(new String(key));
byte[] desText = rc.decrypt(enText);
descrypted = new String(desText);
StringBuilder sb2 = new StringBuilder(128);
sb2.append("UPDATE ").append(jComboBox3.getSelectedItem().toString()).append(" SET ");
sb2.append(box.get(i).getText().toString()+" = ").append("REPLACE ").append("("+box.get(i).getText().toString()+",");
sb2.append("'"+isikolom+"'").append(",");
isideskripsi.stream().forEach(isideskripsi -> {
sb2.append("'"+isideskripsi+"'");
});
sb2.append(")");
String query2 = sb2.toString();
System.out.println(query2);
PreparedStatement presatet2 = con.prepareStatement(query2);
// presatet2.executeUpdate();
}
System.out.println("After Encryption : "+isiencrypsi);
System.out.println("After Descryption : "+isideskripsi);
}
}
end = System.currentTimeMillis();
long time = end - start;
JOptionPane.showMessageDialog(null, "Berhasil Deskripsi Dalam Waktu "+time+" Detik");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Gagal Deskripsi, Error Pada : "+e);
System.out.print(e);
}
arraylist items is [admin, pegawai, penyidik]
this is result of that code :
UPDATE user SET username = REPLACE (username,'X"mBR','admin''pegawai''penyidik')
UPDATE user SET username = REPLACE (username,'I#gJK�','admin''pegawai''penyidik')
UPDATE user SET username = REPLACE (username,' I#nRU� �','admin''pegawai''penyidik')
the results i expected :
UPDATE user SET username = REPLACE (username,'X"mBR','admin')
UPDATE user SET username = REPLACE (username,'I#gJK�','pegawai')
UPDATE user SET username = REPLACE (username,' I#nRU� �','penyidik')
Because your description is not clear, I am not sure what you want to do is as follows:
int idx = 0;
while(rs.next()) {
...
sb2.append("'"+isikolom+"'").append(",");
/* remove this block
isideskripsi.stream().forEach(isideskripsi -> {
sb2.append("'"+isideskripsi+"'");
});
*/
sb2.append("'").append(isideskripsi.get(idx)).append("'");
sb2.append(")");
idx++;
...
}
isideskripsi.stream().forEach(isideskripsi -> {
sb2.append("'"+isideskripsi+"'");
});
The above code problems, because every time you build your SQL, you output all the items inside the arraylist, instead you should:
sb2.append("'"+isideskripsi.get(i-1)+"'");
As you only want every one arraylist item one time

How can i get the specific data from array

My question is when i store the data into array from sqlite database, how can i get it from specific position let say, my database contain "food, drinks,snack" how can i get the string "snack" from array.
String CatNameQuery = "SELECT * FROM Category";
db = new DBController(MainActivity.this);
SQLiteDatabase db3 = db.getReadableDatabase();
final Cursor cursor2 = db3.rawQuery(CatNameQuery, null);
{
List<String> array = new ArrayList<String>();
while(cursor2.moveToNext()){
String uname = cursor2.getString(cursor2.getColumnIndex("CategoryName"));
array.add(uname);
}
You need to iterate through the list in order to find the item you are looking for.
For example:
for (String s : array) {
if (s.equals("snack")) {
System.out.println("Found snack");
}
}
You can also use the contains method to check if the list contains "snack."
if (array.contains("snack")) {
System.out.println("Found snack");
}
Resource: ArrayList
Use the WHERE clause within your SELECT query. For example:
"SELECT * FROM Category WHERE CategoryName='snacks'"
This will fill your array with only items under the category 'snacks'.
List<String> array = new ArrayList<String>();
array.add("food");
array.add("drinks");
array.add("snack");
String result="";
if (array.contains("snack")) // avoid null pointer exception
{
int index =array.indexOf("snack") //find the index of arraylist
result=array.get(index);
}
You can find it by looping the array
List<String> arrobj= new ArrayList<String>();
arrobj.add("food");
arrobj.add("drinks");
arrobj.add("snack");
for (String value : arrobj) {
if (value.equals("snack")) {
System.out.println("Here is the snack");
}
}
if (array.size() > 0) {
int index = 0;
if (array.contains("Snacks")) {
index = array.indexOf("Snacks");
System.out.println(array.get(index));
}
}

Remove words in a string array until it becomes empty

I have "help","me","please" in a String array and I want to remove "help" from the array, i.e. after returning it as a string, remove "me" after returning it as a string, then remove the last one too, thereby making the string array empty.
I used this
public String showCurrentString(){
EditText ed = (EditText)findViewById(R.id.ed);
String edText = ed.getText().toString();
String nn =edText;
String[] blure = nn.split(" ");
int Index = 1;
for(String check : blure){
if(Arrays.asList(blure).contains(edText)){
PlaySound(StringName() + ".mp3");
Toast.makeText(getApplicationContext(),check,Toast.LENGTH_LONG).show();
But I don't know how to delete each word after toasting it.
So my main question is on how to delete a words that have been parsed or (that I have already used) from a string array.
I think you could delete the first word by doing :
nn = nn.substring(nn.indexOf(' '), nn.length);
(You can do it multiple time, just check that nn.trim().length != 0)
Suppose you have following values:
edText = "Help Me Please"
blure[0] = "Help"
blure[1] = "Me"
blure[2] = "Please"
Then this code should work fine for you:
public String showCurrentString(){
EditText ed = (EditText)findViewById(R.id.ed);
String edText = ed.getText().toString();
String nn =edText;
List<String> blure = new LinkedList<String>(Arrays.asList(nn.split("
")));
ListIterator<String> iter = blure.listIterator();
while(iter.hasNext())
{
String itemToBeRemoved = iter.next();
iter.remove();
System.out.println("Removed "+itemToBeRemoved+"!");
}
}

Avoiding comma at the start of .CSV file in java

I am scrapping data from a website and store it in CSV file. When the data gets in the CSV file it was getting the comma at the last place of every line. Somehow I manage to handle it. But, now I am getting that comma at the very start of every line which is creating another column. Following is my code.
for (Iterator<Element> it = tdElements.iterator(); it.hasNext();) {
if (it.hasNext()) {
sb.append(" \n ");
}
for (Iterator<Element> it2 = trElement2.iterator(); it.hasNext();) {
Element tdElement = it.next();
final String content = tdElement.text();
if (it2.hasNext()) {
sb.append(" , ");
sb.append(formatData(content));
}
if (!it2.hasNext()) {
String content1 = content.replaceAll(",$", " ");
sb.append(formatData(content1));
break;
} //to remove last placed Commas.
}
System.out.println(sb.toString());
sb.flush();
sb.close();
Result which I want e.g: a,b,c,d,e
Result which I am getting e.g: ,a,b,c,d,e
If you're developing in Java 8, I suggest that you use StringJoiner. With this new class, you don't have to build the string yourself. You can find an example to create a CSV with StringJoiner here.
I hope it helps.
StringBuffer sb = new StringBuffer(" ");
for (Iterator<Element> it = tdElements.iterator(); it.hasNext();) {
if (it.hasNext()) {
sb.deleteCharAt(sb.length() - 1);
sb.append(" \n ");
}
for (Iterator<Element> it2 = trElement2.iterator(); it.hasNext();) {
Element tdElement = it.next();
final String content = tdElement.text();
if (it2.hasNext()) {
sb.append(formatData(content));
sb.append(",");
}
if (!it2.hasNext()) {
String content1 = content.replaceAll(",$", " ");
sb.append(formatData(content1));
break;
} //to remove last placed Commas.
}
System.out.println(sb.toString());
sb.flush();
sb.close();
}
im trying to remove the last character which in your case is a , at the instance where it is trying to move to a new line try replacing with my code
and make sure to instantiate stringbuffer with a space passed as a string.

writing json file using arrays with large data using java

I am trying to form a json file to source an autocomplete controlled textbox.
The file will have millions of elements so I am trying to eliminate duplicates while saving on memory and time. For small amount the following code works yet since I am using an array, the execution gets really slow as the array gets larger.
int i = 0;
JSONObject obj = new JSONObject();
JSONArray array = new JSONArray();
while (iter.hasNext()) {
Map<String,String>forJson = new HashMap<String, String>();
Statement stmt = iter.nextStatement();
object = stmt.getObject();
forJson.put("key", object.asResource().getLocalName());
forJson.put("value", object.asResource().getURI());
i++;
System.out.println(i);
if(!array.contains(forJson))
{
array.add(forJson);
}
}
obj.put("objects", array);
FileWriter file = new FileWriter("/homeDir/data.json");
file.write(obj.toJSONString());
file.flush();
file.close();
The array.contains control eliminates duplicates but it has a considerable negative effect on execution time.
The json file should have tokens like
[{"key": "exampleText1", "value": "exampleValue1"},
{"key": "exampleText2", "value": "exampleValue2"}]
Use a HashSet to contain the keys you have already added:
...
Set<String> usedKeys = new HashSet<String>();
while (iter.hasNext()) {
Map<String,String>forJson = new HashMap<String, String>();
Statement stmt = iter.nextStatement();
object = stmt.getObject();
String key = object.asResource().getLocalName();
if(!usedKeys.contains(key)) {
usedKeys.add(key);
forJson.put("key", key);
forJson.put("value", object.asResource().getURI());
array.add(forJson);
}
i++;
System.out.println(i);
}
If you need to uniqueness check to include the value, you could append the two using a character separator that you know cannot exist in the keys. For example:
String key = object.asResource().getLocalName();
String value = object.asResource().getURI();
String unique = key + "|#|#|" + value;
if(!usedKeys.contains(unique)) {
usedKeys.add(unique);
forJson.put("key", key);
forJson.put("value", value);
array.add(forJson);
}

Categories