I am getting error on "If(rs.next())" and ".getString" - java

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.

Related

Cant get expected result

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..

Passing ArrayList to separate class?

I have a code that reads from an SQL Database and saves each column of information into an ArrayList. I need to pass each ArrayList into a separate class where I can store the lists as single pieces of information (IE: Information in the first part of ArrayList1 goes with information in the first part of ArrayList2 etc...) and then sort them. I don't know how to pass that information to another class though. This is a section of my main method that stores the information into a list. I need this information passed to a separate class called List.java:
String SelectStatement1 = "SELECT InvoiceID FROM Invoice;";
ps = conn.prepareStatement(SelectStatement1);
rs = ps.executeQuery();
int count = 0;
while (rs.next()){
count++;
}
ps.close();
ps = conn.prepareStatement(SelectStatement1);
rs = ps.executeQuery();
ArrayList<String> InvoiceIDList = new ArrayList<String>();
String InvoiceID = null;
int p = 0;
while (p < count){
rs.next();
InvoiceID = rs.getString("InvoiceID");
InvoiceIDList.add(InvoiceID);
p++;
}
ps.close();
p = 0;
Edit: This is only a section of my code, I already have the code open and close the connections, I only need information on how to pass the ArrayList to another class for sorting.
Create a method in your other class like this:
public void receiveList (ArrayList<String> invoiceIDList) {
// Do something with invoiceIDList data
}
It may not be a bad idea to create a constructor in your "List" class, that accepts the ArrayList and creates the class instance with the required data
Also, please change the name of that class!! It will be confusing to others who read your code, as you are passing an ArrayList already!
EDIT:
You could also have your class implement the List interface, which would make things a lot easier for you, because you can insert data into your class based on the position of the data in the ArrayList.
public class yourClass implements List<String> {
// Your class methods and variables...
}
If you wanted to expand on this to allow more than just Strings, you can change to: List<T>, this would give you a more generic approach.
First, I suggest you perform a SELECT COUNT() instead of iterating your rows in your first query. Then remember to close() both the PreparedStatement and ResultSet. Finally, I would suggest you program to the List<String> interface. Putting it all together like,
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Connect to your database and initialize conn.
int count = 0;
try {
String query1 = "SELECT COUNT(InvoiceID) FROM Invoice;";
ps = conn.prepareStatement(query1);
rs = ps.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (Exception ignored) {
}
try {
ps.close();
} catch (Exception ignored) {
}
}
The above block of code is necessary to close() both rs and ps in the correct order with the finally Block.
List<String> invoiceIdList = new ArrayList<>();
try {
String query2 = "SELECT InvoiceID FROM Invoice;";
ps = conn.prepareStatement(query2);
rs = ps.executeQuery();
while (rs.next()) {
invoiceIdList.add(rs.getString("InvoiceID"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally { // <-- it's identical to the finally block above.
try {
rs.close();
} catch (Exception ignored) {
}
try {
ps.close();
} catch (Exception ignored) {
}
}
// now you can pass invoiceIdList elsewhere...
if (!invoiceIdList.isEmpty()) {
doSomething(invoiceIdList);
}

Printing a query from a database

I am trying to access a database and print off a query.
I am trying to access a DEVICE table and print off the DEVICE_ID, but i am unsuccessful so far.
Here is my code at the moment;
public static void main(String[] args) throws FileNotFoundException {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
Preferences sysRoot = Preferences.systemRoot();
Preferences prefs = sysRoot.node("com/davranetworks/zebu");
url = prefs.get("dburl", "jdbc:hsqldb:E:\\eem\\eemdb");
} catch (Exception e) {
e.printStackTrace();
}
Connection c = getConnection();
try {
c.setAutoCommit(true);
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = s.executeQuery("SELECT * FROM eem_db.device");
ResultSet deviceId = s.executeQuery("select device_id from eem_db.device");
System.out.println(deviceId);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection c = null;
try {
c = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println("Error initialising connection" + e);
}
return c;
}
The returned value is org.hsqldb.jdbc.JDBCResultSet#1d3d68df.
I don't know what this value relates to as I was expecting 3 integer values.
Can anyone help me on this?
You have to iterate over the rows contained in the ResultSet and for each row get the column you want:
ResultSet deviceIdRS = s.executeQuery("select device_id from eem_db.device");
while(deviceIdRS.next()) {
System.out.println(deviceIdRS.getString("device_id"));
}
You must use the ResultSet getXXX method that correspond with your column type, for example, getInt, getString, getDate...
That ResultSet deviceId is actually an object contains rows of result from your sql, so you only can see the memory address when you print it out.
You need something like:
while(deviceId.next()){
System.out.print(deviceId.getInt(1));
}
s.executeQuery("select device_id from eem_db.device"); is returning a resultSet, you must find out the value from result set.
like
int device_id = resultset["deviceId"];
while (deviceId.next())
{
// Printing results to the console
System.out.println("device_id- "+ deviceId.getInt("device_id");
}
iterate object using resultset.
You are printing object of ResultSet, it won't give you the right values.
You need to iterate the loop like below
while(deviceId.next()) {
int integerValue = deviceId.getInt(1);
System.out.println("content" + integerValue)
}
deviceId.close();
s.close();

java how retrieve data from database

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();
}

Problem using generics in function

I have this functions and need to make it one function. The only difference is type of input variable sourceColumnValue. This variable can be String or Integer but the return value of function must be always Integer.
I know I need to use Generics but can't do it.
public Integer selectReturnInt(String tableName, String sourceColumnName, String sourceColumnValue, String targetColumnName) {
Integer returned = null;
String query = "SELECT "+targetColumnName+" FROM "+tableName+" WHERE "+sourceColumnName+"='"+sourceColumnValue+"' LIMIT 1";
try {
Connection connection = ConnectionManager.getInstance().open();
java.sql.Statement statement = connection.createStatement();
statement.execute(query.toString());
ResultSet rs = statement.getResultSet();
while(rs.next()){
returned = rs.getInt(targetColumnName);
}
rs.close();
statement.close();
ConnectionManager.getInstance().close(connection);
} catch (SQLException e) {
System.out.println("Заявката не може да бъде изпълнена!");
System.out.println(e);
}
return returned;
}
// SELECT (RETURN INTEGER)
public Integer selectIntReturnInt(String tableName, String sourceColumnName, Integer sourceColumnValue, String targetColumnName) {
Integer returned = null;
String query = "SELECT "+targetColumnName+" FROM "+tableName+" WHERE "+sourceColumnName+"='"+sourceColumnValue+"' LIMIT 1";
try {
Connection connection = ConnectionManager.getInstance().open();
java.sql.Statement statement = connection.createStatement();
statement.execute(query.toString());
ResultSet rs = statement.getResultSet();
while(rs.next()){
returned = rs.getInt(targetColumnName);
}
rs.close();
statement.close();
ConnectionManager.getInstance().close(connection);
} catch (SQLException e) {
System.out.println("Заявката не може да бъде изпълнена!");
System.out.println(e);
}
return returned;
}
No you don't need to use generics for this.. generic should be used when your supported Types can be to many and you don't know about them before hand and they share something common in them.
Only for just two Types Generics is not a good choice. Using objects can be a better choice.
May be i will say you don't even need to merge these functions, that's what polymorphism is for. keeping things discreet will allow more readability of code
No need to use generic, you can just use Object as the variable type for the function :
public Integer selectIntReturnInt(String tableName, String sourceColumnName, Object sourceColumnValue, String targetColumnName) {
Integer returned = null;
String query = "SELECT "+targetColumnName+" FROM "+tableName+" WHERE "+sourceColumnName+"='"+sourceColumnValue.toString()+"' LIMIT 1";
try {
Connection connection = ConnectionManager.getInstance().open();
java.sql.Statement statement = connection.createStatement();
statement.execute(query.toString());
ResultSet rs = statement.getResultSet();
while(rs.next()){
returned = rs.getInt(targetColumnName);
}
rs.close();
statement.close();
ConnectionManager.getInstance().close(connection);
} catch (SQLException e) {
System.out.println("Заявката не може да бъде изпълнена!");
System.out.println(e);
}
return returned;
}
You don't need to use generics. Just declare it as
public Integer selectReturnInt(String tableName,
String sourceColumnName,
Object sourceColumnValue,
String targetColumnName) {
...
}
For the love $deity please don't use dynamic SQL. You will get injection vulnerabilities.
You want to break this into (at least) three method. One with the bulk of the implementation, and one each for the different types.
Also of note:
Resource handling should be of the form final Resource resource = acquire(); try { ... } finally { resource.release(); }, or in JDK7 try (final Resource resource = acquire()) { ... }.
Singletons are the work of the devil.
Exception handling considered a good idea, whereas sinking to a printf is bad.
You're probably better off only returning a value if there is exactly one result set and throwing an exception otherwise.
Have the second method just call the first:
public Integer selectIntReturnInt(String tableName, String sourceColumnName, Integer sourceColumnValue, String targetColumnName) {
return selectReturnInt(tableName, sourceColumnName, sourceColumnValue.toString(), targetColumnName);
}

Categories