Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQLite database error when try to insert into table

In my project ,add a function to insert elements to data base in a class public class DBHelper extends SQLiteOpenHelper .The function is given below.

public void insertIntoDatabase(String field_one,String field_two){
    String sql = "INSERT INTO UserTable.NAME (COL_USERNAME, COL_PASSWORD) " +
            "VALUES (" + field_one + ", " + field_two + ")";
    db.execSQL(sql);

In main activity read name and password and call the function insert into database

DBHelper dbhelper;



dbhelper.insertIntoDatabase(rdname.getText().toString(), rdpwrd.getText().toString());

But there was an error .

like image 347
mridul Avatar asked Dec 01 '25 12:12

mridul


1 Answers

I pretty recommend to you use API method of SQLiteDatabase db.insert() that is directly designated for inserting new rows to table. This solution is cleaner.

public void insertIntoDatabase(String field_one, String field_two){
   ContentValues data = new ContentValues();
   data.put("COL_USERNAME", field_one);
   data.put("COL_PASSWORD", field_two);
   if (db == null) {
      // make sure that your db is properly initialised
   }
   db.insert("tablename", "nullColumnHack", data);
}

Explanation of nullColumnHack:

If your provided values is empty, no column names are known and an empty row can't be inserted. If not set to null, the nullColumnHack parameter provides the name of nullable column name to explicitly insert a NULL into in the case where your values is empty.

It means that in Android SQLite you have to specify one column that will be assign NULL to in the case if you pass empty ContentValues.

If you want to use your approach i recommend to you an usage of placeholders.

String sql = "INSERT INTO UserTable.NAME (COL_USERNAME, COL_PASSWORD) " +
            "VALUES (?, ?)";
    db.execSQL(sql, new String[] {field_one, field_two});

Note: Probably it didn't work because you didn't use single quotes.

VALUES ("' + field_one + '", "' + field_two + '")"

And also make sure that given tablename is correct. I recommend to create static variables which will hold tablename and column names.

public static final String TABLE_NAME = "Table";
String query = "insert into " + ClassName.TABLE_NAME + " values(?, ?)"
like image 62
Simon Dorociak Avatar answered Dec 04 '25 05:12

Simon Dorociak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!