This is coding I needed to implement in my project when I am calling method getClassId() in my servlet it returns one and first value from the table however table contains many records.When I use System.out.println(rs.getString(clId)) ; in getClassId() method it displays correct output. Simply I can Say it does not iterate only once through rs.getString() when I call getClassName() in getClassId().
public List<String> getClassId() {
Statement stmt = null;
List<String> stList = new ArrayList<String>();
try {
Con = conManager.getConnection();
stmt = Con.createStatement();
String query = "SELECT * FROM classes";
rs=stmt.executeQuery(query);
while(rs.next()) {
stList = getClassName(rs.getString(clId));
}
} catch(Exception e) {
System.out.println(e);
}
return stList;
}
public String getClassName(String id) {
String str = "";
Statement stmt = null;
try {
Con = conManager.getConnection();
stmt = Con.createStatement();
String query = "SELECT * FROM classes where clId="+id;
rs=stmt.executeQuery(query);
while(rs.next()) {
str = rs.getString("className");
}
} catch(Exception e) {
System.out.println(e);
}
return str;
}
The getClassName() method here returns the className value in the last row found in the database resultset as :
while(rs.next()){
str = rs.getString("className");
}
Clearly str contains the last value in the resultset.
Now getClassId() method invokes getClassName() by iteratively passing the values of clId but in the getClassId() method, you are reassigning the value to stList as given below [even this should fail at the time of compilation as String value cannot be assigned to a List datatype..Please check]:
while(rs.next() ){
stList = getClassName(rs.getString(clId));
}
Instead try using the below code :
while(rs.next()){
stList.add(getClassName(rs.getString(clId)));
}
This will add all the values returned by getclassName() to the arrayList.
Hope that helps..
Related
I am getting error in if(rs.next()) and .getString on my code. This is my code
public void keyPressed(KeyEvent e) {
Function f = new Function();
Result rs = null;
String ans = "Key";
rs = f.find(jTextField1.getText());
try{
if(rs.next()){
jTextArea1.setText(rs.getString("Key"));
}
}catch(Exception ex){
}
}
OK the methods next() and getString() are parts of the java.sql.ResultSet interface. Your code should look like this:
public void keyPressed(KeyEvent e) {
Function f = new Function();
ResultSet rs = null;
String ans = "Key";
rs = f.find(jTextField1.getText());
try{
if(rs.next()){
jTextArea1.setText(rs.getString("Key"));
}
}catch(Exception ex){}
}
And if the Function objects method find(String search) returns a valid java.sql.ResultSet implementation, you can use next() to move pointer to next Result and to check if it has one. And then you can easyly use getString(String columnName) to get the value of a column as String.
I would return ResultSet in an method like this. Let your Function class method find directly return your desired value or null or empty string. Handling the ResultSet here isn't good practice. Keep your concerns together.
The return type is an array of String. I returned that array but still the error message is shown.
public static String[] get_dept_list()
{
establishConnection();
try
{
stmt = conn.createStatement();
sql = "select * from DEPARTMENT_LIST";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("Query Ran");
int in=-1;
String name [] = {};
while(rs.next())
{
in++;
}
rs = stmt.executeQuery(sql);
name = new String [in+1];
in=-1;
while(rs.next())
{
name[++in] = rs.getString("DEPT_NAME");
}
return name;
}
catch (SQLException e)
{
System.out.println("Problem in finding the dept_name_list");
}
}
When the exception is caught, you have to make sure to return an array too.
catch (SQLException e)
{
System.out.println("Problem in finding the dept_name_list");
return new String[] { };
}
You have an error message because your only return is on your try - catch block. Try to put one in your catch or outside the try - catch.
The error message is telling you that the method must return a String[].
In the case were an exception is thrown and you enter your catch statement, no return is made.
Either refactor your code to return a default String[] or allow the exception to propagate.
You have to add a return null or a return new String[] { }; at the end of your function.
If you get an SQLException, your code won't return anything. You are probably getting one.
Verify the console for any outputs and put a return statement inside the catch or after it.
What if the code throws SQLExecption? The control will reach to the catch block and then after the catch block, there is no return statement.
Change your code to something like this:
public static String[] get_dept_list()
String [] name = null;
try {
...
name = new String [in+1];
...
} catch (SQLException e) {
...
}
return name;
}
So irrespective of whether the code will throw exception, the last line of the method will always be executed and thus you are making sure that your method always returns a String array.
move your name variable declaration above try - catch block
and re-assign it to null when exception occures, as it is easier to check null condition
public static String[] get_dept_list()
{
String name [] = null;
establishConnection();
try
{
stmt = conn.createStatement();
sql = "select * from DEPARTMENT_LIST";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("Query Ran");
int in=-1;
while(rs.next())
{
in++;
}
rs = stmt.executeQuery(sql);
name = new String [in+1];
in=-1;
while(rs.next())
{
name[++in] = rs.getString("DEPT_NAME");
}
}
catch (SQLException e)
{
System.out.println("Problem in finding the dept_name_list");
name = null;
}finally{
//close resource intensive connection
if(stmt != null){
stmt.close();
}
if(conn!= null){
conn.close();
}
}
return name;
}
I have code
public static String getData(String query) {
String output = "";
try {
String connectionUrl = "jdbc:sqlserver://localhost:1234;databaseName=123;user=123;password=123";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "select smth from tableName where smth";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
output = (String) rs.getObject(1);
}
rs.close();
}
catch (Exception e) {
return "ERROR while retrieving data: " + e.getMessage();
}
return output;
}
It works if value is string. But if it integer? Or boolean? How to modify this method so it would be universal, no matter what type data I get I still return it as string?
First retreive the result in ResultSet rs,
then you can write the code like below.
You can check the instance of the object and than assign the value.
String str;
Object obj = (Object)rs.getObject(1);
if(obj instanceof String){
//do you work here for string like below
str=(String)obj;
}
else if (obj instanceof Integer){
//do your work for Integer
}
// same you can do for other types
in this line
output = (String) rs.getObject(1);
if string then use
output = rs.getString(1);
if int
output = rs.getInt(1);
click oracle for more info
You can't accurately do that without using ResultSetMetaData class to get the column type.
Get the column data according to the type of the column.
You are getting the value from the resultset presuming that it is always a String and trying to typecast the Object instance. You should make use of the retrieve methods based on the type. Most of the cases, we will be knowing the datatype of the column values from which we retried the data. You can write the program based on the column's type. that's why ResultSet API has a method for each datatype.
For String
rs.getString(1);
For Int
rs.getInt(1)
Please read the documentation of ResultSet
while (rs.next())
{
String[] data;
data = new String[100];
data[i] = rs.getString("smth");
i = i + 1;
}
Try this you got your data in array.. use array instead of object.
what about toString()?
while (rs.next()) {
output = rs.getObject(1).toString();
}
I want to count the numbers of entries in resultset and then store these values in an array and pass this array to create a graph.
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename"); // this statement will select the unique entries in a
particular column provided by jtextfield
int count=0;
while(rs.next())
{ ++count; } // This will count the number of entries in the result set.
Now I want to store the values of result set in an array of string. I used the following code
String[] row = new String[count];
while(rs.next())
{
for (int i=0; i <columnCount ; i++)
{
row[i] = rs.getString(i + 1);
}
}
Error : Invalid Descriptor Index.
Please suggest how to copy the result of resultset in array.
For example if I enter priority in jTextField , the result set will contain
priority1
priority2
priority3
In your first while loop you read all the entries in the ResultSet, so when executing the second while loop there's nothing else to read. Also, the index of ResultSet#getXxx starts at 1, not at 0. Also, since you don't know the amount of rows that you will read, it will be better using a List backed by ArrayList instead.
Considering these, your code should look like:
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+
" as call from tablename");
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
Based in your comment, I extended the sample:
public List<String> yourRandomQuery(String columnName) {
Connection con = null;
ResultSet rs = null;
List<String> results = new ArrayList<String>();
try {
String baseQuery = "SELECT DISTINCT %s AS call FROM tablename";
con = ...; //retrieve your connection
ResultSet rs = stmt.executeQuery(String.format(baseQuery, columnName));
while(rs.next()) {
results.add(rs.getString(1));
}
} catch (SQLException e) {
//handle your exception
e.printStacktrace(System.out);
} finally {
closeResource(rs);
closeResource(con);
}
return results;
}
//both Connection and ResultSet interfaces extends from AutoCloseable interface
public void closeResource(AutoCloseable ac) {
try {
if (ac != null) {
ac.close();
}
} catch (Exception e) {
//handle this exception as well...
}
}
public void someMethod() {
//retrieve the results from database
List<String> results = yourRandomQuery(jTextField.getText());
//consume the results as you wish
//basic example: printing them in the console
for(String result : results) {
System.out.println(result);
}
}
Try this
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename");
List<String> list=new ArrayList<>();
while(rs.next())
{
list.add(rs.getString(1));
}
Why not just create a HashSet<String> and write into that. Note that HashSet is unordered, just like your query. By using a collection that is of arbitrary size you don't need to determine the require dsize in advance.
I have a my main class, a DTO, and a DAO.
what I want to do is to read the database table CUSTOMER(two fields NAME, SURNAME) then write it to a txt file. I cant seem to get it to store the values in the DTO so that my main class can get it.
My DTO exist of two fields, NAME and SURNAME with the getters and setters.
The problem lies in my DAO with the List
*please keep in mind I'm a student.
This is what I have done so far:
result, writes to file like this: [name surname, name surname, name surname,]
I need it to write to the file pipe deliminated " | "
public CustomerDTO getDetails(Connection conn) throws SQLException {
CustomerDTO customerDTO = new CustomerDTO();
ResultSet rs = null;
PreparedStatement pstmnt = null;
try {
// SELECT NAME, SURNAME FROM CUSTOMER
StringBuffer stringBuffer = new StringBuffer("SELECT " + DBConstants.CUST_NAME + ", ");
stringBuffer.append(DBConstants.CUST_SURNAME);
stringBuffer.append(" FROM " + "CUSTOMER");
//build string
String query = stringBuffer.toString();
//prepared statement
pstmnt = conn.prepareStatement(query);
//execute preparestatement
rs = pstmnt.executeQuery();
//keep reading next line in table - .next() method means next line
List myList = new ArrayList();
while (rs.next()) {
String ss = rs.getString("NAME");
String sss = rs.getString("SURNAME");
myList.add(ss + " " + sss);
customerDTO.setName(myList.toString());
customerDTO.setSurname(myList.toString());
}
} catch (Exception e) {
e.getMessage();
}
rs.close();
//return DTO with details.
return customerDTO;
}
I am not sure where or how you are writing this file is but in tracing the code, here is what I think might be wrong.
In this WHILE LOOP:
while (rs.next()) {
String ss = rs.getString("NAME");
String sss = rs.getString("SURNAME");
// You'r adding an element here that would have a value like this: "John Doe"
myList.add(ss + " " + sss);
// Single instance of a DTO whose value. State values will always be replaced with the
// string represenation of the myList variable.
//
// Both properties will always contain the same value no matter what.
customerDTO.setName(myList.toString());
customerDTO.setSurname(myList.toString());
}
I think what you should really be doing is something like this:
// Notice the use of Generics (Look it up). It is more compile time safe and better practice.
ArrayList<CustomerDTO> customerDTOS = new ArrayList<CustomerDTO>();
while (rs.next()) {
String ss = rs.getString("NAME");
String sss = rs.getString("SURNAME");
CustomerDTO customerDTO = new CustomerDTO();
customerDTO.setName(ss);
customerDTO.setSurName(sss);
customerDTOS.Add(customerDTO);
}
return customerDTOS;
In short, your method should return a list of CustomerDTOs and then you can use them to write to your file.
Good Luck.
The method should be declared as
public List<CustomerDTO> getDetails(Connection conn) throws SQLException {
...
}
since its goal is to return a list of customers (one per row in the table).
Inside the method, you should have the following:
// create the result list, initially empty
List<CustomerDTO> result = new ArrayList<CustomerDTO>();
// iterate through the rows
while (rs.next()) {
// TODO: create a new CustomerDTO, and populate it with the row's data
// TODO: add this DTO to the result list
}
return result;
Then, the caller of this method will iterate through the list of CustomerDTOs, and write them to a file. Each method has its responsibility: the DAO handles the database retrieval, but doesn't handle the file IO.
here's a complete example:
public void caller() {
Connection conn = null;
// TODO: setup connection
List list = getDetails(conn);
for (int i=0; i<list.size(); i++) {
CustomerDTO dto = list.get(i);
write(dto.getName(), dto.getSurname());
}
}
public List getDetails(Connection conn) throws SQLException {
List myList = new ArrayList();
ResultSet rs = null;
PreparedStatement pstmnt = null;
try {
// SELECT NAME, SURNAME FROM CUSTOMER
StringBuffer stringBuffer = new StringBuffer("SELECT " + DBConstants.CUST_NAME + ", ");
stringBuffer.append(DBConstants.CUST_SURNAME);
stringBuffer.append(" FROM " + "CUSTOMER");
//build string
String query = stringBuffer.toString();
//prepared statement
pstmnt = conn.prepareStatement(query);
//execute preparestatement
rs = pstmnt.executeQuery();
//keep reading next line in table - .next() method means next line
while (rs.next()) {
String ss = rs.getString("NAME");
String sss = rs.getString("SURNAME");
CustomerDTO customerDTO = new CustomerDTO();
customerDTO.setName(ss);
customerDTO.setSurname(sss);
myList.add(customerDTO);
}
} catch (Exception e) {
e.getMessage();
}
rs.close();
//return list of DTOs.
return myList;
}
I leave the implementation of the write method to you.
Also. consider using Generics if your java allows it.