Convert Resultset to String array - java

I need to Convert My result set to an array of Strings. I am reading Email addresses from the database and I need to be able to send them like:
message.addRecipient(Message.RecipientType.CC, "abc#abc.com,abc#def.com,ghi#abc.com");
Here is My code for reading the Email addresses:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test {
public static void main(String[] args) {
Connection conn = null;
String iphost = "localhost";
String dbsid = "ASKDB";
String username = "ASKUL";
String password = "askul";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String sql = "SELECT * FROM EMAIL";
conn = DriverManager.getConnection("jdbc:oracle:thin:#" + iphost + ":1521:" + dbsid, username, password);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
String[] arr = null;
while (rs.next()) {
String em = rs.getString("EM_ID");
arr = em.split("\n");
for (int i =0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
} catch (Exception asd) {
System.out.println(asd);
}
}
}
MyOutput is:
myemailaddress#abc.com
myotheremail#abc.com
I need it like this:
myemailaddress#abc.com,myotheremail#abc.com
I am using Oracle 11g.

to get the desired output:
replace these lines
String[] arr = null;
while (rs.next()) {
String em = rs.getString("EM_ID");
arr = em.split("\n");
for (int i =0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
by
String arr = null;
while (rs.next()) {
String em = rs.getString("EM_ID");
arr = em.replace("\n", ",");
System.out.println(arr);
}

System.out.println(arr[i]);
Instead use:
System.out.print(arr[i] + ",");

If i understand correctly You want to see the output in one line with comma as a separator.
Then instead of
System.out.println(arr[i]);
Try
System.out.print(arr[i]+",");
and remove last comma somehow.

you do not need arr = em.split("\n"); since you are looping through each row (assuming that 1 row = 1 email address ) you just need this :
ArrayList<String> arr = new ArrayList<String>();
while (rs.next()) {
arr.add(rs.getString("EM_ID"));
System.out.println(arr.get(arr.size()-1));
}

import java.util.List;
import java.util.ArrayList;
List<String> listEmail = new ArrayList<String>();
while (rs.next()) {
listEmail.add(rs.getString("EM_ID"));
}
//listEmail,toString() will look like this: [abc#abc.com, abc#def.com]
//So lets replace the brackets and remove the whitspaces
//You can do this in less steps if you want:
String result = listEmail.toString();
result = result.replace("[", "\"");
result = result.replace("]", "\"");
result = result.replace(" ", "");
//your result: "abc#abc.com,abc#def.com"
//If the spaces are e problem just use the string function to remove them
Btw you may should use BCC instead of CC in terms of privacy....
Also you should never use
SELECT * FROM foo;
Better use
SELECT EM_ID FROM foo;
This gives you a significant Performance increase in a huge Table, since the ResultSet just consists of the information you really need and use...

Related

remove last word continuously and check in database table java

i have a small translation program to develop. The user input a sentence and the sentence is then check in a table in my database. if the sentence to sentence match is found. it displays the result else it removes the last word of the sentence and rechecks until a match is found or until one word is left( to be developed) . i have a small implementation for the handling of sentence to sentence match but i am having a small problem with my loop. i cannot figure out out to make it work. I know the problem is the the else part of loop i cannot figure out how to do it. I am not sure if the compiler will even loop back for the truncated sentence.
String sentence = "i am a good boy";
for(int j=0;j<sentence.length();j++)
{
if(sentence.length()>1)
{
sentence = lookUpSentencePart(sentence);
rs2 = sentenceDBQuery(sentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
System.out.println("mon pass dan rs1 true");
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
else
{
sentence = lookUpSentencePart(sentence);
rs2 = sentenceDBQuery(sentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
}
}
}
public String lookUpSentencePart(String sentence)
{
sentence = sentence.substring(0, sentence.lastIndexOf(" "));
return sentence;
}
public ResultSet sentenceDBQuery(String sentence, String source, String target)
{
ResultSet rs = null;
Statement stmt;
myConnection db = new myConnection();
try
{
Connection myConn = db.theconnect();
stmt = myConn.createStatement();
rs = stmt.executeQuery("SELECT " + target + " from sentence WHERE " + source + " = '" + sentence+"'");
}
catch(SQLException e)
{
e.printStackTrace();
}
return rs;
}
Probably you need smth like that :) You still need to add some boundary checks
String[] sentence = "i am a good boy".split(" ");
for(int j=0;j<sentence.length;j++)
{
String realSentence = buildSentence(sentence, j);
rs2 = sentenceDBQuery(realSentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
System.out.println("mon pass dan rs1 true");
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
}
public String buildSentence(String[] parts, int index) {
StringBuilder result = new StringBuilder();
for (int j = 0; j < (parts.length - index); j++) {
sb.append(parts[j]).append(" ");
}
sb.setLength(sb.length() - 1);
return result.toString();
}

Make this program more efficient?

just curious if anyone has any idea for making this program more simple. It reads records from a database into an ArrayList and allows the user to search for records by state. It processes a database of 1 million records in aprox 16000ms.
import java.sql.*;
import java.util.*;
public class ShowEmployeeDB
{
public static void main(String args[])
{
ArrayList <String> Recs = new ArrayList <String>();
String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
String connectionURL = "jdbc:odbc:CitizensDB";
Connection con = null;
Statement stmt = null;
String sqlStatement = "SELECT * FROM Citizens";
ResultSet rs = null;
int r = 0;
Scanner scan = new Scanner(System.in);
String search = null;
long starttime = System.currentTimeMillis();
try
{
Class.forName(driverName).newInstance();
con = DriverManager.getConnection(connectionURL);
stmt = con.createStatement();
rs = stmt.executeQuery(sqlStatement);
String ID = null;
String Age = null;
String State = null;
String Gender = null;
String Status = null;
String record = null;
while (rs.next())
{
for (int k = 1; k <= 1; ++k)
{
ID = rs.getString(k) + " ";
for (int j = 2; j <= 2; ++j)
Age = rs.getString(j) + " ";
for (int i = 3; i <= 3; ++i)
State = rs.getString(i).toUpperCase() + " ";
for (int h = 4; h <= 4; ++h)
Gender = rs.getString(h) + " ";
for (int g = 5; g <= 5; ++g)
Status = rs.getString(g) + " ";
}//for
record = ID + Age + State + Gender + Status;
Recs.add(record);
++r;
}//while
rs.close();
stmt.close();
con.close();
} catch (Exception ex) { ex.printStackTrace(); }
String endtime = System.currentTimeMillis() - starttime + "ms";
System.out.println(endtime);
System.out.print("Enter A Search State: ");
search = scan.nextLine().toUpperCase();
Iterator<String> iter = Recs.iterator();
while(iter.hasNext())
{
String s = iter.next();
if (s.contains(search))
{
System.out.println(s);
}
}//while
} // main
} // ShowEmployeeBD
Any advice would be greatly appreciated. Thank you in advance!
If search is not often, I would suggest to take the search string input before running the query, so that search results are directly from the DB. I this case you do not have to reiterate all 1 million records.
Perform searching directly on DB rather than fetching all the records and searching through java code.
Also if search is on multiple column, then prepare a meta data in DB at a single place on the basis of IDs, and the meta data can further be used for fetching the required results that match the query.
Separate your logic from the technical stuff. In such a convolut it is difficult to run unit tests or any optimizations.
Why do you need for loops, when only asking one value.
Use StringBuilder instead of String concatenation.
Use either try-with or put your close statements in a finally clause.
Don't initialize variables you don't need (r).
Use for each statements.
Query the database, not the result set.
Tune your database.
If you are only searching for a state, filter only those, so build an object and compare the state instead of a string contains.
Compare the state before storing strings in the list.
Tune your list because it constantly grows with 1Mio records.
Use a hashset instead of an arraylist.
Develop against interfaces.
A better program might look like following:
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class ShowEmployeeDB {
private static final String DRIVERNAME = "sun.jdbc.odbc.JdbcOdbcDriver";
private static final String CONNECTIONURL = "jdbc:odbc:CitizensDB";
private static final String SELECT_CITIZENS = "SELECT * FROM Citizens";
static {
try {
DriverManager.registerDriver((Driver) Class.forName(DRIVERNAME).newInstance());
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
public static void main(final String args[]) {
System.out.print("Enter A Search State: ");
searchRecords();
}
private static void searchRecords() {
try(Scanner scan = new Scanner(System.in);) {
final String state = scan.nextLine();
final long starttime = System.currentTimeMillis();
final Set<Record> records = searchRecordsByState(state);
System.out.println(System.currentTimeMillis() - starttime + "ms");
for(final Record r : records) {
System.out.println(r);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Set<Record> searchRecordsByState(final String stateToFilter) {
final Set<Record> records = new HashSet<>();
try(Connection con = DriverManager.getConnection(CONNECTIONURL);
PreparedStatement stmt = con.prepareStatement(SELECT_CITIZENS);
ResultSet rs = stmt.executeQuery(); ) {
while(rs.next()) {
final String state = rs.getString(3);
if(state.equalsIgnoreCase(stateToFilter)) {
final Record r = new Record(rs.getString(1), rs.getString(2), state, rs.getString(4), rs.getString(5));
records.add(r);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return records;
}
}
class Record {
String id, age, state, gender, status;
public Record(String id, String age, String state, String gender, String status) {
this.id = id;
this.age = age;
this.state = state;
this.gender = gender;
this.status = status;
}
public String getState() {
return state;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(id).append(' ')
.append(age).append(' ')
.append(state).append(' ')
.append(gender).append(' ')
.append(status);
return sb.toString();
}
}
This is untested, because I don't have a database with a million entries by hand.
But the best would be to query the database and catch only those entries you need. So use the WHERE-clause in your statement.

How to generate random code and check whether it exist in database or not

I try to generate random code name as licenseKey and check whether it is exist in database or not. If not exist, then display in my jsp page, if exist, continue generating the random code. I got the error "java.lang.StackOverflowError". How to solve this? Below is my code :
package com.raydar.hospital;
import com.raydar.hospital.DB_Connection;
import java.sql.*;
public class RandomCodeGenerator {
String licenseKey = "";
int noOfCAPSAlpha = 4;
int noOfDigits = 4;
int minLen = 8;
int maxLen = 8;
char[] code = RandomCode.generateCode(minLen, maxLen, noOfCAPSAlpha, noOfDigits);
public RandomCodeGenerator(){
}
public String getOutputCode() throws Exception{
String result ="";
result = isLicenseKeyExist();
System.out.println("4 + " +result);
if (result=="false"){
System.out.println("1 + " +new String(code));
licenseKey = new String(code);
}
else if (result=="true"){
System.out.println("2 + " +new String(code));
licenseKey = new String(code);
isLicenseKeyExist ();
}
return licenseKey;
}
private String isLicenseKeyExist () throws Exception{
String code = "";
code = getOutputCode();
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
String result="";
System.out.println("3 + " +code);
try{
DB_Connection connect = new DB_Connection();
connection = connect.getDBConnection();
statement = connection.createStatement();
rs = statement.executeQuery("SELECT licenseKey FROM hospital WHERE licenseKey = '" +code+ "'");
if (rs.next()){
result = "true";
}
else{
result = "false";
}
}catch (Exception e){
System.out.println("Error retrieving data! "+e);
}
return result;
}
}
You create a recursive loop where isLicenseKeyExist() calls getOutputCode(), but then getOutputCode() calls isLicenseKeyExist(). So eventually you run out of stack space, and get this exception.
Here,
public String getOutputCode() throws Exception{
String result ="";
result = isLicenseKeyExist();
...
}
private String isLicenseKeyExist () throws Exception{
String code = "";
code = getOutputCode();
...
}
I think you want something like this. Remove the field called code from your class, and its initialiser, and put the call to RandomCode.generateCode inside your getOutputCode method like this. The reason is that you'll have to call it repeatedly if your code is already in the database.
public String getOutputCode() throws SQLException {
String code;
do {
code = new String(RandomCode.generateCode(minLen, maxLen, noOfCAPSAlpha, noOfDigits));
}
while(licenceKeyExists(code));
return code;
}
private boolean licenceKeyExists(String code) throws SQLException {
try{
DB_Connection connect = new DB_Connection();
connection = connect.getDBConnection();
statement = connection.createStatement();
rs = statement.executeQuery("SELECT licenseKey FROM hospital WHERE licenseKey = '" +code+ "'");
return rs.next();
}
finally {
try {
connection.close();
} catch (SQLException ignored){}
}
}
#aween - #captureSteve has answered the first part of the question .
So, straight to "I wan't to call this function" comment. See, if I
understand your question correctly, you want to generate a key, and
check if it is available in the DB using isLicenseKeyExist() . In such
case, why don't you create the key first, then pass it to the
isLicenseKeyExist(). Then this function will return true/false based
on which you can decide what to do.

How to sort excel using arraylist in java and jdbc

I have an excel spreadsheet with data in just the first 2 columns. I want to sort the data into an array so that I can loop through and perform calculations with the data.
So far, I've been able to just output the content of the spreadsheet to the console log. I am very new to Java programming and I need help.
This the code I have thus far:
import java.sql.*;
import java.util.*;
public class testJDBC {
public static void main(String[] args) {
//private static List<DataItem> myList = ArrayList<DataItem>();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Sample_Defects");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select * from [Sheet1$]");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while (rs.next()) {
//DataItem d = new DataItem();
// d.setID(rs.getString(1));
// d.setSTATUS(rs.getString(2));
//myList.add(d);
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) System.out.print(" , " );
String columnValue = rs.getString(i);
System.out.print(columnValue);
}
System.out.println();
}
st.close();
con.close();
} catch (Exception ex) {
System.err.print("Exception: ");
System.err.println(ex.getMessage());
}
}
}
You can insert the data in a 2D array. and then sort it.
Something like - String[][] array = new String[2][numberOfColumns];
Then you can use the Arrays.sort() method to sort. you can also override the method to get your desired sorting like -
Arrays.sort(array, new Comparator<String[]>() {
public int compare(String[] a, String[] b) {
return a[0].compareTo(b[0]);
}
});

Pass A resultset outside the While Loop in Java

Hello friends i have this class that is getting values from the database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailAlerts {
public static void main(String[] args) {
SMTPAuthenticator sm = new SMTPAuthenticator();//new class
Connection conn = null;
String AtmName = "";
String AtmBal = "";
String atmsend = "";
String[] bals = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#192.168.1.80:1521:dev9i", "BI", "bi");
Statement st1 = conn.createStatement();
String atms = "select CLR_BAL_AMT, FORACID, ACCT_NAME from gam "
+ "where BACID = 'ATM' and CLR_BAL_AMT < 100000";
ResultSet rs1 = st1.executeQuery(atms);
while (rs1.next()) {
AtmName = rs1.getString("ACCT_NAME");
AtmBal = rs1.getString("CLR_BAL_AMT");
bals = AtmBal.split("\n");
for (int j = 0; j < bals.length; j++) {
atmsend = AtmName + "-" + AtmBal;
//System.out.println(atmsend);
}
}
System.out.println(atmsend);
}catch(Exception ad){
System.out.println(ad);
}
}
}
When I try to print out the variable "atmsend" outside the While loop, it only gives the last value in the database but inside the for loop, all the records from the database are there. How can I have all the records on the database outside the While loop?
If you want to put in the variable atmsend all the values from the database, change this code:
atmsend = AtmName + "-" + AtmBal;
to this, although it is not recommended:
atmsend += AtmName + "-" + AtmBal + "\n";
You could use an ArrayList<String> and add all the values inside it while iterating them, instead of using a String
atmsend = atmsend + AtmName + "-" + AtmBal +"\n";
ArrayList <String> atmsend= new ArrayList<>();
Use Arraylist
while (rs1.next()) {
AtmName = rs1.getString("ACCT_NAME");
AtmBal = rs1.getString("CLR_BAL_AMT");
bals = AtmBal.split("\n");
for (int j = 0; j < bals.length; j++) {
atmsend.add(AtmName + "-" + AtmBal+"\n");
//System.out.println(atmsend);
}
System.out.println(atmsend.toString());
declare atmsend as String array
String[] atmsend = null;
now when you store the value inside the while loop use
atmsend[i] = AtmName + "-" + AtmBal;
to retireve the string results
for(int i=0;i<atmsend.length();i++)
{
SYstem.out.println(atmsend[i]);
}

Categories

Resources