SQLite Check if column exist or not - java

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

Related

SQLite can't find column of letter strings but can of number strings - E/SQLiteLog: (1) no such column: (subjectName variable)

When the subjectName variable is a string with letters the function doesn't delete the item from the database and throws this error: E/SQLiteLog: (1) no such column: (subjectName variable)
But when the subjectName variable is a numeric string everything works fine, i dont know why
please help
public void deleteLesson(Button buttonLesson) {
String buttonLessonText = buttonLesson.getText().toString();
try {
SQLiteDatabase myDatabase = this.openOrCreateDatabase("LearnUp", MODE_PRIVATE, null);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS lessons (lesson VARCHAR, year INT(4))");
Cursor c = myDatabase.rawQuery("SELECT * FROM lessons", null);
int subjectIndex = c.getColumnIndex("subject");
int lessonIndex = c.getColumnIndex("lesson");
c.moveToFirst();
while (c != null) {
String tempName = c.getString(subjectIndex);
if (subjectName.matches(tempName)) {
Log.i("Info", subjectName+tempName);
myDatabase.delete("Lessons", "Lesson = ? AND Subject =" + subjectName, new String[] {buttonLessonText});
}
c.moveToNext();
}
}
catch (Exception e) {
}
}

SQL: Can't get count(*) to work - why so?

I'm trying to query a database for the count of entries that match the given ID, but I can't come up with a working solution.
There are two of each type of account that correspond to the userID of 1, for some reason the first method outputs "1" and the second "0". I can show the mainactivity and the database shchema if needed as well.
public int numberOfDebitAccounts(int userID){
int numOf_accs = 0;
String query = "select count(*) from debitAccount where userID = '" +userID+"'";
openDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
numOf_accs = cursor.getInt(0);
System.out.println("Number of debit accs: " + numOf_accs);
}
cursor.close();
closeDatabase();
return numOf_accs;
}
public int numberOfCreditAccounts(int userID){
int numOf_accs = 0;
String query = "select count(accountID) from creditAccount where userID = '" +userID+"'";
openDatabase();
Cursor cursor = db.rawQuery(query,null);
if(cursor.moveToFirst()) {
numOf_accs = cursor.getInt(0);
System.out.println("number of credit accounts: " + numOf_accs);
}
closeDatabase();
return numOf_accs;
}

Trying to hide null values from being printed

How do I hide null values from being printed? I have one Products table which has 5 columns. ID, Dairy, Fruit, Vegetables, Grains, and Protein.
When I search for dairy it brings up null values. Whats the best way to hide it?
public String dbToStringDairy() {
SQLiteDatabase db = getWritableDatabase();
String dbStringDairy = "";
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex(COLUMN_ID)) != null) {
dbStringDairy += " ";
dbStringDairy += c.getString(c.getColumnIndex(COLUMN_PRODUCT_DAIRY));
dbStringDairy += "\n";
}
c.moveToNext();
}
db.close();
return dbStringDairy;
}
The Simplest way to return something else instead of null, using an if else statement to check if the return result is null or not, if it is null store something else so that the program wont return and print null.
Here some simple example:
public String dbToStringDairy()
{
SQLiteDatabase db = getWritableDatabase();
String dbStringDairy = "";
String query = "SELECT * FROM " + TABLE_NAME + " WHERE 1";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast())
{
if(c.getString(c.getColumnIndex(COLUMN_ID))!=null)
{
dbStringDairy += " ";
dbStringDairy += c.getString(c.getColumnIndex(COLUMN_PRODUCT_DAIRY));
dbStringDairy += "\n";
}
c.moveToNext();
}
db.close();
//Replace the `null` into other useful information
if(dbStringDairy==null){
dbStringDairy="No Results";
}
return dbStringDairy;
}
There are a lot of way to ensure your program won't print out null value. This method perform in the dbToStringDairy(), there is also way to do it during your Print Implementation.
Anywhere, hope this simple solution could help.

SQLite database query returns only one row

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

Android/Java : Is my code correct?

I am trying to make a simple login System. And This is the coed in database class. Is my Method correct? It should return true if both username and password are correct and false if either one of them is wrong or not in the database(not registered)? Is there any simpler way to code this method?
public boolean getAccount(String name, String password) {
int test = 0;
database = getReadableDatabase();
String sql = "SELECT * FROM tbl_account WHERE username='name' AND password='password'";
Cursor c = database.rawQuery(sql, null);
if (c.moveToFirst()) {
do {
if (c.getString(0).isEmpty()) {
test = 0;
}
else if (c.getString(0).isEmpty() == false) {
if (name.equals(c.getString(0))) {
if (c.getString(1).isEmpty()) {
test = 0;
}
else if (password.equals(c.getString(1))) {
test = 1;
}
}
}
} while (c.moveToNext());
}
if (test == 0) {
return false;
} else {
return true;
}
}
Best practice is to use ? placeholders with selection arguments where you can:
String sql = "SELECT * FROM tbl_account WHERE username = ? AND password = ?";
Cursor c = database.rawQuery(sql, new String[] {name, password});
This avoids problems where the arguments themselves contain characters such as quotes and apostophes that could otherwise break your constructed SQL string.
I think your sql should be:
String sql = "SELECT * FROM tbl_account WHERE username='" + name +
"' AND password='" + password + "'";
try this sql. hope it will help.

Categories

Resources