I'm new to android and I created a database and I have an id as an integer primary key autoincrement
but I check on the email attribute when I register a new acc on the application, but I have a problem with the sql query that I can't put my hand on.
So I got this error today on this method that calls the name from the database using the email, and I hope you can tell me what's wrong!
E/MessageQueue-JNI: android.database.sqlite.SQLiteException: near ".": syntax error (code 1 SQLITE_ERROR): , while compiling: SELECT user_name FROM USER_TABLE WHERE user_email = androidx.appcompat.widget.AppCompatEditText{3c496d9 VFED..CL. ........ 0,0-656,127 #7f0a0068 app:id/email}
Here's the method:
public String getName(String mail) {
String nameReturn="Name";
SQLiteDatabase db=getWritableDatabase();
Cursor cursor=db.rawQuery("SELECT user_name FROM USER_TABLE WHERE user_email = "+mail, null);
if(cursor.moveToFirst()) nameReturn = cursor.getString(0);
return nameReturn.toString();
}
Looks like you are passing the EditText view to the query. Just pass the text itself
editTextView.getText()
Because your condition is string. So you must set into single quote
Cursor cursor=db.rawQuery("SELECT user_name FROM USER_TABLE WHERE user_email = '"+mail +"'", null);
Or you can use this type:
String[] args = {mail};
String sql = "SELECT user_name FROM USER_TABLE WHERE user_email =?";
Cursor cursor= db.rawQuery(sql, args);
Related
I am trying to create a fitness app where the database saves a username and password.
then enters their details that saves to a second table. This is my dbHelper.
The error im getting is that my "Username Column does not exist"
But when i go and look at my tables using db browser for sqlite
it shows my tables created and data in my tables
UPDATE : I created 1 table to store all my data and now its not picking up still im getting "not set" from my display method
updated table
// Register table
public static final String COL_1 = "ID";
public static final String COL_2 = "Username";
public static final String COL_3 = "Password";
public static final String COL_4 = "Weight";
public static final String COL_5 = "Height";
public static final String COL_6 = "TargetWeight";
public static final String COL_7 = "TargetSteps";
display method
public String DisplayData(String username,String column)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME +" WHERE Username =?",new String[]{username});
if(cursor.moveToFirst()){
return cursor.getString(cursor.getColumnIndexOrThrow(column));
}else{
return "Not set";
}
}
Usage
public void setData() {
db = new dbHelper(this);
try {
userWeight.setText(db.DisplayData(Username, dbHelper.COL_4));
userHeight.setText(db.DisplayData(Username, dbHelper.COL_5));
userTargetWeight.setText(db.DisplayData(Username, dbHelper.COL_6));
userTargetSteps.setText(db.DisplayData(Username, dbHelper.COL_7));
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
TABLE_NAME1 has no Username column. update your method as follow
public String DisplayData(String username, String column) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME +" WHERE " + column + " = ? ", new String[]{username});
if (cursor != null && cursor.moveToFirst()){
return cursor.getString(cursor.getColumnIndexOrThrow(column));
} else {
return "Not set";
}
}
and use it like this
.DisplayData("admin", "Username");
Your issue, assuming that value of the 2nd argument of the Displaydata method is Username is that you are querying TABLE_NAME1 (profile_data) table, which doesn't have a column named Username.
Instead I believe you want to be querying the TABLE_NAME (register_table table) table so change :-
Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME1 +" WHERE Username = 'admin' ",null);
to :-
Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME +" WHERE Username = 'admin' ",null);
Additional re comment :-
Im not longer getting an error but its still not displaying the
correcting infomation . Im getting "Not set " from my displayData
method. from my if ELSE
Assuming that you have added data and getting the above then it is likely that Username does not equate to a row in the table. Try using the following version of DisplayData to debug :-
// Note changed to use recommended convenience query method
// Note closes cursor thus uses intermediate variable (rv) to allow close
public String DisplayData(String username,String column)
{
String rv = "Not set";
SQLiteDatabase db = this.getReadableDatabase();
//Cursor cursor = db.rawQuery("SELECT * FROM "+ TABLE_NAME +" WHERE Username =?",new String[]{username}); //<<<<< replaced
String whereclause = COL_2 + "=?";
String[] whereargs = new String[]{username};
Cursor cursor = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
//<<<<<<<<<< FOLLOWING CODE ADDED TO LOG DEBUG INFO >>>>>>>>>>
Log.d("DISPLAYDATAINFO","Display was called with Username as:- " +
username +
" for Column:- " +
column +
". The Cursor contains " +
String.valueOf(cursor.getCount()) +
" ."
);
//<<<<<<<<<< END OF ADDED DEBUG CODE >>>>>>>>>>
if(cursor.moveToFirst()){
rv = cursor.getString(cursor.getColumnIndexOrThrow(column));
}
cursor.close(); //<<<< SHOULD ALWAYS CLOSE CURSOR WHEN DONE WITH IT
return rv;
}
This should produce output in the log along the lines of :-
05-18 23:08:25.429 2926-2926/fitness.fitness D/DISPLAYDATAINFO: Display was called with Username as:- Fred for Column:- Weight. The Cursor contains 5 .
Display was called with Username as:- Fred for Column:- Height. The Cursor contains 5 .
Display was called with Username as:- Fred for Column:- TargetWeight. The Cursor contains 5 .
Display was called with Username as:- Fred for Column:- TargetSteps. The Cursor contains 5 .
Note 5 because when testing new data is inserted each run so the above indicates the 5th run.
Or in the case of nothing being found (your current issue) something like :-
05-18 23:11:40.342 2926-2926/fitness.fitness D/DISPLAYDATAINFO: Display was called with Username as:- Tom for Column:- Weight. The Cursor contains 0 .
Display was called with Username as:- Tom for Column:- Height. The Cursor contains 0 .
Display was called with Username as:- Tom for Column:- TargetWeight. The Cursor contains 0 .
Display was called with Username as:- Tom for Column:- TargetSteps. The Cursor contains 0 .
i.e. Cursor contains 0 = no rows exist for the given username (Tom in this case).
Check if the Username is as expected (note case of letters must match, in the above a row for tom exists but not for Tom hence 0 count for the cursor).
Column retrieval appears to be correct, However, still check that the columns in the output are as expected (can't see that they would not be).
I'm working very well with the SQLite database, but now I have a problem while using a query.
For example, if use a query like this:
SQLiteDatabase db = mHelper.getReadableDatabase();
String parameter = mypar;
String sql = SELECT color, name FROM table WHERE name = '" + parameter + "';
Cursor c = db.rawQuery(sql, null);
while (c.moveToNext()) {
String color = c.getString(0);
String name = c.getString(1);
}
c.close();
db.close();
Everything works fine
But if the parameter has an apex
String parameter = mypar';
I get an exception
Caused by: android.database.sqlite.SQLiteException: near "r": syntax error (code 1):
How can I solve this problem? Thank you
this is my solution, works fine!! try it
String parameter = mypar';
String sql = SELECT color, name FROM table WHERE name = ?;
Cursor c = db.rawQuery(sql, new String[] { parameter });
I wrote the following code to insert some records into table from the table of another database.
But I'm unable to, even after executing a sql statement it shows that there are no records in the table.
public int copy_to_all_source_table(String dbpath,String backpath)
{
SQLiteDatabase db1 = this.getWritableDatabase();
//Opening App database(i.e. dbpath) and attaching it as "OLD"
db1.openDatabase(dbpath, null, SQLiteDatabase.OPEN_READWRITE);
String attach_old="ATTACH '"+ dbpath +"' AS OLD";
db1.execSQL(attach_old);
//Opening New File which is Student.db(i.e. dbpath) and attaching it as "NEW"
db1.openDatabase(backpath, null, SQLiteDatabase.OPEN_READWRITE);
String attach_new="ATTACH '"+ backpath +"' AS NEW";
db1.execSQL(attach_new);
// Getting count of records in table of "NEW"
String new_query =" SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
Cursor new_data = db1.rawQuery(new_query, null);
Integer new_count= new_data.getCount();
//INSERTING ALL RECORDS FROM TABLE OF NEW TO TABLE OF OLD
String insert_query ="INSERT INTO 'OLD'.'"+ TABLE_CONTACTS +"' SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
Cursor success_insert = db1.rawQuery(insert_query, null);
// Getting count of records in table of "NEW"
String after_insert_old_query =" SELECT * FROM 'OLD'.'"+ TABLE_CONTACTS +"'";
Cursor old_data = db1.rawQuery(after_insert_old_query, null);
Integer old_count= old_data.getCount();
}
RESULT:
new_count = 11
old_count = 0
So, no record has been inserted.
You are using rawQuery() to execute an INSERT command. Which will never work.
Use execSQL(), instead
Moreover, the last comment is misleading, because it says you want the count from the NEW table, but you are counting from the OLD one.
And, please, get rid of the string delimiter characters (').
I.e.:
this
String new_query =" SELECT * FROM 'NEW'.'"+ TABLE_CONTACTS +"'";
should be
String new_query = "SELECT * FROM NEW." + TABLE_CONTACTS;
I've written the following DB query.
However, the app crashes when I access the list activity that displays the results.
I've traced the error to the method below (other simpler query methods work just fine):
public Cursor fetchInterface_HSE_Entries(String string) throws SQLException{
String[] columns = new String[] {KEY_ROW_ID_INTERFACE, KEY_TEXTVIEW_VALUE, KEY_CATEGORY_OPTIONS, KEY_WORKSCREEN};
String whereClause = KEY_WORKSCREEN+"=" + string;
Cursor cursor = db.query(TEXTVIEWS_TABLE, columns, whereClause, null, null, null, null);
if(cursor != null){
cursor.moveToFirst();
}
return cursor;
}
And this is part of my error log:
12-31 16:13:38.851: E/AndroidRuntime(480): Caused by: android.database.sqlite.SQLiteException: no such column: testInterface1: , while compiling: SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen=testInterface1
Try with:
String whereClause = KEY_WORKSCREEN+"='" + string + "'";
You need to quote text values in your queries, otherwise they will be interpreted as column names (or functions, or whatever).
Note that this is not safe against SQL Injection attacks, you should be using bind variables.
String whereClause = KEY_WORKSCREEN+" = ?";
Cursor cursor = db.query(TEXTVIEWS_TABLE, columns, whereClause,
new String[]{string}, null, null, null);
Because you do not put quotes around your whereClause.
Try:
String whereClause = KEY_WORKSCREEN+"='" + string + "'";
You can clearly see it in your error log:
SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen=testInterface1
should be:
SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen='testInterface1'
SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen=testInterface1
As error says you don't have testInterface1 collumn in interfacetable table, i think you should have value instead of testInterface1 in your sql statement. Run your query in db, and you will see the same error.
You need to put your string value in the where clause into quotes.
Workscren is string edit your query and add single quotes. Key-workscreen+"="'+ string +'" like that
I am getting an error with a rawquery on Eclipse on a DB in the assets directory. The DB is 'pre-loaded' with tables and data and the SQL string, first comment line, works in SQLite DB browser. When I copy the SQL string to code and modify to remove quotes it errors. The code below is from the 'standard' public class DataBaseHelper extends SQLiteOpenHelper{ .I am new to android/java and would appreciate any assistance or suggestions.
public Cursor getAllSectionDescriptions( String DBtable, String source){
//Works in DB: SELECT "Description" FROM "SectionProps" WHERE Source = "UK"
//String q = "SELECT Description FROM SectionProps WHERE Source = UK " ; <= errors in code
String q = "SELECT Description FROM " + DBtable + " WHERE Source = " + source + " "; //<== errors in code
//06-24 16:53:03.373: ERROR/AndroidRuntime(1000): Caused by: android.database.sqlite.SQLiteException: no such table: SectionProps: , while compiling: SELECT Description FROM SectionProps WHERE Source = UK
Cursor mCursor = myDataBase.rawQuery(q, null);
mCursor.moveToFirst();
return mCursor;
}//end cursor
Looks like you have to put double quotes around your object names. So you'll want to do this:
String q = "SELECT \"Description\" FROM \"" + DBtable + "\" WHERE Source = \"" + source + "\" ";
Note the double quotes preceded by the escape character '\'
To execute queries, there are two methods: Execute db.rawQuery method Execute db.query method To execute a raw query to retrieve all departments:
Cursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id,
"+colDeptName+" from "+deptTable,new String [] {});
return cur;
}
The rawQuery method has two parameters: String query: The select statement String[] selection args: The arguments if a WHERE clause is included in the select statement Notes The result of a query is returned in Cursor object. In a select statement if the primary key column (the id column) of the table has a name other than _id, then you have to use an alias in the form SELECT [Column Name] as _id cause the Cursor object always expects that the primary key column has the name _id or it will throw an exception .