Retrieving all data from a Database Column - java

Is there a method in which I can retrieve all the data from a particular database column and store it in a string array?
My database currently looks like this:
public class DatabaseTotalEntries {
public static final String KEY_ROWID = "_id";
public static final String KEY_NAME = "appliance_name";
public static final String KEY_TOTAL_TIME = "appliance_running_time";
public static final String KEY_TOTAL_COST = "appliance_cost_usage";
public static final String KEY_TOTAL_ENERGY = "appliance_energy_usage";
private static final String DATABASE_NAME = "ApplianceTotaldb"; // The name of the database
private static final String DATABASE_TABLE = "AllEntries"; // The name of the database table
private static final int DATABASE_VERSION = 1;
and I am looking to create a method in which the data under the column 'KEY_TOTAL_COST' for every row/entry in the database is retrieved and stored in a String array
Any hep would be appreciated

Use standard way to retrieve data from DB via JDBC driver for your database. Create prepared statement, execute it upon created connection and pull data from result set object. As mentioned in Mihai Todor's answer, in SQL query, select only KEY_TOTAL_COST, it will be faster if you query only for columns that you're interested in. When you pull data from result set, you can put it into whatever data structure you want, and manipulate it as you need (truncate, split, convert to numbers and so on ...)
You might find this tutorial useful:
http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
... or simply try looking on google for more of "JDBC result set" usage examples.

Well, the SQL statement that you need to use is this: select appliance_running_time from ApplianceTotaldb.AllEntries. In order to run it, I guess it depends on the RDBMS that you are using. Is it MySQL? Try to search for a JDBC tutorial on Google...

Related

ORMLite Java, casing of sequences

I am trying to connect to postgresql with ORMlite from a Java client.
the DB gets generated perfectly, but when I try to insert something into a table that is using an autoincrement id I get the following error:
org.postgresql.util.PSQLException: ERROR: relation "commandusage_id_seq" does not exist
When I check the DB I can see a "commandUsage_id_seq" sequence has been created. With a Capital U.
How can I configure ORMLite to use all the same casing for both creating and interacting with the DB ? I couldn't find this in the documentation
Thanks in advace.
update:
When explicitly setting the sequenceId I can circumvent the issue
generatedIdSequence = "commandusage_id_seq"
but still I would like to know if this is possible by setting some config for ORMLite instead of setting this per DBObject class
update2:
URL of the package to prevent confusion: ORMLite
update3:
Below a snippet of the code and how it works. Again I would like to know if ORMLite is capable of doing the to lowercase conversion automatically instead of me doing it explicitly.
#DatabaseTable(tableName = "commandusage", daoClass = CommandUsageDaoImpl.class)
public class CommandUsage {
#DatabaseField(columnName = "id", generatedIdSequence = "commandusage_id_seq")
private transient int identifier;
When I check the DB I can see a "commandUsage_id_seq" sequence has been created. With a Capital U.
Interesting. After some initial confusion on my part, this seems like a bug a in ORMLite. The pattern is if you force a table name with mixed case (typical is to downcase the name) and then ask for a sequence-id on it in Postgresql:
#DatabaseTable(tableName = "TableNameCaseWithSeqeuence")
private static class TableNameCaseWithSeqeuence {
#DatabaseField(generatedId = true)
public int id;
...
}
I've got a fix in trunk but it's going to take a bit to spin a release.
The workaround right now is to extend the PostgresDatabaseType and inject it into your ConnectionSource. It should do something like:
public OurPostgresDatabaseType extends PostgresDatabaseType {
// constructors ...
#Override
public String generateIdSequenceName(String tableName, FieldType idType) {
String name = tableName + DEFAULT_SEQUENCE_SUFFIX;
return downCaseString(name, true);
}
}

SQLite query statements in separate file

I'm developing an Android application and I would like to keep my SQLite query statements outside of my Java classes.
I considered using a .properties file, in which to store all of my SQL statements. Sounds fine, each property in a .properties file holds a string - I can even store prepared statements and give them the needed parameters, for example:
get.student.with.first.name=SELECT * FROM Students WHERE FirstName = ?;
However, I have also implemented Persistence Contracts for my database tables like so:
public final class StudentPersistenceContract {
private StudentPersistenceContract() {}
public static abstract class StudentEntry implements BaseColumns {
public static final String TABLE_NAME = "Student";
public static final String COLUMN_FIRST_NAME = "FirstName";
public static final String COLUMN_LAST_NAME = "LastName";
}
}
I wouldn't want to hardcode the table and column names into the entries of the .properties file, I would like to access them dynamically like so: StudentPersistenceContract.StudentEntry.TABLE_NAME, etc.
One thing I thought of was creating a class which can't be instantiated in which to "construct" the queries I need. Something along the lines of...
public final class SqlQueryConstructor {
private SqlQueryConstructor() {}
public static final String GET_STUDENT_WITH_FIRST_NAME = "SELECT * FROM " + StudentPersistenceContract.StudentEntry.TABLE_NAME + " WHERE " + StudentPersistenceContract.StudentEntry.COLUMN_FIRST_NAME + " = ?;";
}
This way I can get the desired SQL query by accessing: SqlQueryConstructor.GET_STUDENT_WITH_FIRST_NAME
This is still a Java class, but it'll be good to know that all of my SQL is there and not scattered around all over the place.
Is this a good idea? Are there any other alternatives?
I have decided to use my second approach - using a class with static fields for the SQLite statements. I read about when it's good to use strings.xml and when to use static final Strings: android - strings.xml vs static constants, Android strings, Should I use strings.xml or java strings, etc.
So I'll use strings.xml for localization and the class with static fields for the SQL statements.

Java enum for use across class

I am having trouble declaring an enumeration for DB field types that I can use across all functions of a particular class. With the following code I get "cannot resolve USERNAME to a variable type":
public class SQL_access {
public enum DBfields { BLANK, USERNAME, ID, PASSWORD, FIRSTNAME, LASTNAME };
public boolean loginValidate( String username, String password ){
String DBuser, DBpass;
PreparedStatement table = connectToTable( "firstsql", "users");
ResultSet row = table.executeQuery();;
while(row.next()){
DBuser = row.getString(USERNAME);
if(DBuser.equals(username)){
DBpass = row.getString(PASSWORD);
break;
}
}
}
};
You need to use DBfields.USERNAME.
UPDATE:
in order to use with the getString(String) method, you need to use the name of the enum, like: Dbfields.USERNAME.name().
if you are using the enums only for the jdbc API access, you would be better off just using a String constant:
public static final String DBFIELD_USERNAME = "USERNAME";
You need to reference the enum Type: DBfields.USERNAME, or statically import the enum like:
import static mypackage.SQL_access.DBfields.*;
Also, in your case, this is not enough. You need to pass the column name -- a String -- or the column position -- an int -- to the ResultSet:
row.getString(DBfields.USERNAME.name());
Used like this, you loose the main advantage of enums which is it's static nature, but it can still be useful in other places in your code if you refer to these values as a "bag".
You should access the enum by using DBfields.USERNAME.
See the Oracle Docs for more information.
Try qualifying the enumerator with the enum type:
while(row.next()){
DBuser = row.getString( DBfields.USERNAME);
if(DBuser.equals(username)){
DBpass = row.getString( DBfields.PASSWORD);
break;
}
}
When you reference an enumeration it is always in this form EnumName.Field. In your example you need the following:
DBUser = row.getString(DBfields.USERNAME);
DBpass=row.getString(DBfields.PASSWORD);
to access your enumbs use DBfields.USERNAME, but this will not help you, bacuse row.getString() needs an int as argument. Your Enumbs are of the Type DBFields not int.
better use public static final int USERNAME = the int value here; and call with row.getString(USERNAME);.
Wrong way.You need to call the enum using DBfields.PASSWORD.
You need to call like this: DBfields.PASSWORD

Java - Constants class design

I'm new to Android & Java programming but have been programming in .NET for many years. We've recently developed an android app and it's now in the final stage to be prepped for the customer (not via the market/google play btw). At any rate, while cleaning up the code. I've noticed we use a TON of strings and I'd like to cut down on this if possible. I've read a few articles and took the suggestion that anything the end-user may see, I put it in the strings.xml (for better localization, not too sure what they mean by that) but we also use SQLite table names, column names, etc. and I'd like to know the best way to construct a class (or set of classes) that allows us (my developers and I) to access them with ease.
This is how I started to construct it but wanted some opinions as to if there's a better way (design, performance issues, etc.)
public class Constants {
static enum SQLiteTableNames { Issues, Activities }
static class SQLiteTables {
static class Issues {
static class ColumnNames {
static String ID = "_id";
static String DateReceived = "DateReceived";
}
}
static class IssueActivites {
static class ColumnNames {
static String ID = "_id";
static String IssueID = "IssueID";
static String ActivityDate = "ActivityDate";
static String ActivityType = "ActivityType";
static String FullName = "FullName";
static String Notes = "Notes";
}
}
}
}
This allows us to reference column names like so:
Constants.SQLiteTables.IssueActivites.ColumnNames.ActivityDate;
Should I use final static on the properties instead of just static?
Constants should be static final. This does have a performance benefit, as it allows the value to be compiled in. It's also just good style.
By the way, the convention is to put constant names in ALL_CAPS.

Dynamic variable names Java

How will I be able to retrieve the value of a variable which has a dynamic name
For Example I have list of constants
public class Constant{
public static final String S_R = "Standard(240)";
public static final String S_W = "Standard(180)";
public static final String L_R = "Large(360)";
public static final String L_W = "Large(280)";
}
Based on database I build a variable name
String varName = "S" + "_" +"R"; // This can be S_R , S_W , L_R or L_W
String varVal = // How do i get value of S_R
Use a normal HashMap with variable names as strings against their values. Or use a EnumMap with enums as key and your value as values. AFAIK, that's the closest you can get when using Java. Sure, you can mess around with reflection but IMO the map approach is much more logical.
You can use a Map<String, String> and locate the value by its key.
Even better, you can have an enum:
public enum Foo {
S_R("Standard", 240),
S_W("Standard", 180),...;
private String type;
private String duration;
// constructor and getters
}
And then call Foo.valueOf(name)
(You can also do this via reflection - Constants.class.getField(fieldName) and then call field.get(null) (null for static). But that's not really a good approach.)
If you really must do this (and it's unlikely), you would have to use the Java "reflection" APIs.

Categories

Resources