SQLite database query returns only one row - java

Below is the code I'm using to grab all results stored in an SQLite table. The problem I am having is that it is only returning a single row when I know there are 21 rows in the DB.
public HashMap<String, String> fetchResults(String TABLE_NAME, String sql) {
HashMap<String, String> table = new HashMap<String, String>();
if(sql == null)
sql = "";
String selectQuery = "SELECT * FROM " + TABLE_NAME + " " + sql;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
String[] columns = null;
switch(TABLE_NAME ){
case "projects":
columns = dbTables.projectsColumns;
break;
}
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
int n=1;
for(int i=0; i<columns.length; i++){
table.put(columns[i], cursor.getString(n));
n++;
}
}
//move to the next row
cursor.moveToNext();
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching " + TABLE_NAME + " from Sqlite: " + table.toString());
return table;
}
The db call is made within a fragment and look like this.
HashMap<String, String> projects = db.fetchResults(dbTables.TABLE_PROJECTS, null);
for (String key : projects.keySet()) {
if(key == "projectname"){
System.out.println("Key: " + key + ", Value: " + projects.get(key));
menuList.add(projects.get(key));
}
}

You are only retrieving one single row there:
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
int n=1;
for(int i=0; i<columns.length; i++){
table.put(columns[i], cursor.getString(n));
n++;
}
}
You have to iterate the cursor to get all results:
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
while(cursor.moveToNext()) {
for (int i = 0; i < columns.length; i++) {
table.put(columns[i], cursor.getString(i));
}
}
}
But your table would list all the column values of every row. If you want to have a table with row-entries, define a class for storing the column values.

I am unsure on what the cursor.movetonext() method is because I have never used it, but I would just been using a method like this:
public static ResultSet createRS(String Query,String Server) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://"+Server+"\\SQLExpress;databaseName=Schedule;" +
"integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns a
// set of data and then display it.
String SQL = Query;
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
return rs;
}
With the result set you can just do this:
try {
while (rs.next()) {
current=Double.parseDouble(rs.getString(currentColumn));
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
}

Thanks to all who answered. I have found a function that works for perfectly.
public Cursor getAllRows(String TABLE_NAME, String sql){
String selectQuery = "SELECT * FROM " + TABLE_NAME + " " + sql;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor != null){
cursor.moveToFirst();
}
return cursor;
}

Related

Resultset always empty when doing executeQuery

I am currently writing a simple Java app that reads information from an XLS file and then enters it in the database. Since that XLS does have duplicated records, I do a simple check if the entry in the XLS file already exists in the database. Here is my code:
public static void addResult(ArrayList<ArrayList<String>> listResults)
{
try
{
openDatabase();
stmt = c.createStatement();
for (int i = 0; i < listResults.size(); i++)
{
PreparedStatement stm = c.prepareStatement("SELECT player_name FROM results WHERE player_name=?;");
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
System.out.println(stm);
ResultSet rs = stm.executeQuery();
if (rs.getRow() <= 0)
{
String typeOfPlay = new String();
if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Simple"))
{
typeOfPlay = "single";
}
else if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Double"))
{
typeOfPlay = "double";
}
stm = c.prepareStatement("INSERT INTO results (player_name, school_id, " + typeOfPlay + ", tournament_id) "
+ "VALUES(?,?,?,?);");
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
stm.setString(2, listResults.get(i).get(ReadResultsFile.SCHOOL_ID));
stm.setInt(3, Integer.parseInt(listResults.get(i).get(ReadResultsFile.SCORE)));
stm.setString(4, "1");
stm.executeUpdate();
}
else
{
String typeOfPlay = new String();
if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Simple"))
{
typeOfPlay = "single";
}
else if (listResults.get(i).get(ReadResultsFile.TYPE).equals("Double"))
{
typeOfPlay = "double";
}
stm = c.prepareStatement("UPDATE results SET " + typeOfPlay + "=? WHERE player_name=?;");
stm.setString(1, typeOfPlay);
stm.setString(2, listResults.get(i).get(ReadResultsFile.SCORE));
stm.setString(1, listResults.get(i).get(ReadResultsFile.NAME));
System.out.println(stm);
stm.executeUpdate();
}
}
closeDatabase();
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
The problem that arises is that the rs.getRow() function always returns -1. I tried running the SELECT query directly in the database tool and the query returns the player_name column if there is already a similar entry existing. It unfortunately do the same in Java.
I am unsure what to do at this point.
Thank you for any hint!
getRow will not work as per the javadocs
Retrieves the current row number. The first row is number 1, the second number 2, and so on.
and
A ResultSet cursor is initially positioned before the first row; the
first call to the method next makes the first row the current row
Usually use
while (rs.next ()) {....

Trying to retrieve multiple records from db and add those to JSON array. but for every loop json array is getting cleared

getting values and trying to add to json array
public JSONArray getChooseContact(Context context ,String userid,String bookid , String chapterid, String questionid ) {
DBHelper dbh = new DBHelper(context , LektzDB.DB_NAME, null,
LektzDB.DB_VERSION);
SQLiteDatabase db = dbh.getReadableDatabase();
JSONArray resultSet = new JSONArray();
try{
Cursor cursor = db.rawQuery("SELECT * FROM "
+ TB_AssessmentChooseValues.NAME + " where "
+ TB_AssessmentChooseValues.CL_1_USER_ID + "='"+ userid +"' AND "
+ TB_AssessmentChooseValues.CL_2_BOOK_ID + "='"+ bookid +"' AND "
+ TB_AssessmentChooseValues.CL_3_CHAPTER_ID + "='" + chapterid +"' AND "
+ TB_AssessmentChooseValues.CL_4_QUESTION_ID + "='" + questionid + "'",null);
Log.i("logchoose", "gettingchooseSuccessful");
if(cursor.getCount() > 0) {
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
rowObject.put(cursor.getColumnName(i),
cursor.getString(i));
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
}
}
catch(Exception e)
{
}
return resultSet;
}
and trying to retrieve values as
JSONArray RetrievedChoose = rdb.getChooseContact(getContext(),userid, BookId ,chapter_idchoose ,question_idchoose);
finalassessment.add(String.valueOf(RetrievedChoose));
Log.d("logchoose", "getsuccess"+finalassessment)
The cursor will get two rows of output but in json array im able to get only one value at a time.. I need this operation multiple times in my project please suggest me how to set that json array is not to be replaced for every time
The result is showing two seperate values which firstone is replacing second one
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
rowObject.put(cursor.getColumnName(i),
cursor.getString(i));
} catch (Exception e) {
Log.d("TAG", e.getMessage());
}
}
}
resultSet.put(rowObject);
}
cursor.close();
}
Use above code and return resultSet

SQLite Check if column exist or not

I want to check columns (not value) at agregasi table, if columns exist do something, but if columns does not exist show/print message 'Column does not exist'.
I could run code below while columns exist:
String keywords1={'pesawat','terbang'};
String sql1 = "SELECT " + keywords + " FROM agregasi"; //columns exist at agregasi table
Cursor c1 = myDbHelper.rawQuery(sql1, null);
if (c1.moveToFirst()) {
// i can do something (no problem)
}
But i have problem when columns name i change on purpose (to check). What should i do to print error message (in android/java way)?
**String keywords2={'psawat','terang'};**
String sql2 = "SELECT " + keywords + " FROM agregasi"; //columns does not exist at table
Cursor c2 = myDbHelper.rawQuery(sql2, null);
// what should i do get error message and show/print using toast
You're looking for getColumnIndex(String columnName).
int index = c2.getColumnIndex("someColumnName");
if (index == -1) {
// Column doesn't exist
} else {
...
}
Here's a general method you can use to check whether a particular column exists in a particular table:
public boolean isColumnExists(SQLiteDatabase sqliteDatabase,
String tableName,
String columnToFind) {
Cursor cursor = null;
try {
cursor = sqLiteDatabase.rawQuery(
"PRAGMA table_info(" + tableName + ")",
null
);
int nameColumnIndex = cursor.getColumnIndexOrThrow("name");
while (cursor.moveToNext()) {
String name = cursor.getString(nameColumnIndex);
if (name.equals(columnToFind)) {
return true;
}
}
return false;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
Try this it works fine :)
Cursor res = db.rawQuery("PRAGMA table_info("+tableName+")",null);
int value = res.getColumnIndex(fieldName);

How to make one mySQL's table column invisible

I am running a query on ID column but I don't want it to be visible in my frame/pane. How can I achieve this? Shall I make another table, is there a function in sql/mysql which allows to hide columns? I tried to google it but havent found anything yet.
Here is the code:
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
Connection connection = TableWithBottomLine.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
connection.setAutoCommit(false);
stmt = connection.createStatement();
stmt.addBatch("update finance.fin set " + stulpPav + " = " + duom
+ " where ID = " + studId + ";");
stmt.executeBatch();
connection.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
connection.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
int rowCount;
Object data [][];
String columnNames [];
public MyTableModel() throws SQLException{
String query ="SELECT ID, tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport, Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
ResultSet rs ;
Connection connection = TableWithBottomLine.getConnection();
Statement stmt = null;
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][11];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getInt("ID");
data[iEil][1] = rs.getDate("Date");
data[iEil][2] = rs.getFloat("Flat");
data[iEil][3] = rs.getFloat("Mobile");
data[iEil][4] = rs.getFloat("Food");
data[iEil][5] = rs.getFloat("Alcohol");
data[iEil][6] = rs.getFloat("Transport");
data[iEil][7] = rs.getFloat("Outdoor");
data[iEil][8] = rs.getFloat("Pauls_stuff");
data[iEil][9] = rs.getFloat("Income");
data[iEil][10] = rs.getFloat("Stuff");
}
String[] columnName = {"ID", "Date","Flat","Mobile"
,"Food","Alcohol","Transport", "Outdoor", "Pauls_stuff", "Income", "Stuff"};
columnNames = columnName;
}
This has solved my problem:
table.removeColumn(table.getColumnModel().getColumn(0));
I placed this in my class contructor. This lets remove the column from the view of the table but column 'ID' is still contained in the TableModel. I found that many people looking for an option to exclude specific column (like autoincrement) from SELECT statement in sql / mysql but the language itself doesn't have that feature. So I hope this solution will help others as well.
Don't put ID in the select part of the query
String query ="SELECT tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport,
Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";

populate SWT table with database content

I am using PhpMyAdmin to save my data in database. I have a SWT table to populate with database content.
here is my code..
public static void fetchDatafromDB(String StartIndex, String FinalIndex) {
try {
Class.forName(GlobalVariables.SQL_driver).newInstance();
Connection conn = DriverManager.getConnection(GlobalVariables.DB_url + GlobalVariables.DB_name, GlobalVariables.DB_Username, GlobalVariables.DB_password);
Statement st = conn.createStatement();
String query = "SELECT `From`, `To`, `IDno`, `TimeStamp` FROM `callsheet` WHERE TimeStamp BETWEEN '" + StartIndex + "' AND '" + FinalIndex + "'";
ResultSet rs = st.executeQuery(query);
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= columnsNumber; i++) {
// System.out.print(rs.getString(i));
item.setText(i, rs.getString(i));
}
// System.out.println();
}
} catch (Exception P) {
P.printStackTrace();
}
}
it worked.
Now I am getting some problem with tabling the DB content in my swt table. What my program does, is that, it sets the selected (defined by limit in program above) content of DB in one row (one by one manner) but I want the next row of DB table to be tabled in next row of SWT table. Could you suggest something about this? ! Screenshot of my swtTable
It should look something like this:
public static void fetchDatafromDB(String startIndex, String finalIndex) {
try {
Class.forName(GlobalVariables.SQL_driver).newInstance();
Connection conn = DriverManager.getConnection(GlobalVariables.DB_url + GlobalVariables.DB_name, GlobalVariables.DB_Username, GlobalVariables.DB_password);
Statement st = conn.createStatement();
String query = "SELECT `FROM`, `To`, `IDno`, `TimeStamp` FROM `callsheet` WHERE TimeStamp BETWEEN '" + startIndex + "' AND '" + finalIndex + "'";
ResultSet rs = st.executeQuery(query);
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
TableItem item;
while (rs.next()) {
// Create a new TableItem for each entry in the result set (each row)
item = new TableItem(table, SWT.NONE);
for (int i = 1; i <= columnsNumber; i++) {
// Populate the item (mind the index!!)
item.setText(i - 1, rs.getString(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

Categories

Resources