How to make AUTO_INCREMENT on Android SQLite database?

后端 未结 4 1559
无人共我
无人共我 2020-12-15 19:01

Hey I want to create a database with an AUTO_INCREMENT column. But I don\'t know how to parse the value in the method insert. I just don\'t know what to parse to an AUTO_INC

相关标签:
4条回答
  • 2020-12-15 19:50

    You don't have to specifically write AUTO_INCREMENT as in MYSQL.

    Just have to define the primary key Field as _id INTEGER PRIMARY KEY.

    It will not work, if have define the Primary key field with INT when creating the table. It Should be INTEGER and thats it.

    When you don't pass any value for the primary key filed when inserting records, it will automatically increase the value to be a unique value( same way MYSQL AUTO_INCREMENT works )

    0 讨论(0)
  • 2020-12-15 19:52
    this.db.insert(NULL , 1, contactName, numType, contactNumber,
                        duration, callDate, currTime);
    
    0 讨论(0)
  • 2020-12-15 19:55

    You don't have to parse anything. If the column was created as AUTOINCREMENT, just pass the other values:

    db.execSQL("insert into "
            + TABLE_NAME
            + "(contact_id, contact_name, number_type, contact_number, duration, date, current_time, cont) "
            + "values( "+ cId + ", " + cName + ", " + numType + ", "
            + cNum + ", " + dur + ", " + date + ", " + currTime + ", ? )");
    

    By the way, it's always recommended to insert data using the Android's insert method:

    ContentValues values = new ContentValues();
    values.put("contact_id", cId);
    values.put("contact_name", cName);
    // etc.
    db.insert(TABLE_NAME, null, values);
    
    0 讨论(0)
  • 2020-12-15 20:07
    final static String Database_name="empDb.db";
    
    public DatabaseHelper(Context context) {
        super(context, Database_name, null, 1);
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table emp_tbl (id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,salary TEXT)");
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS tbl_emp");
    }
    

    Get More Info https://www.youtube.com/watch?v=W8-Z85oPNmQ

    Blog: https://itmulc.blogspot.com/2016/08/android-sqlite-database-with-complete.html

    0 讨论(0)
提交回复
热议问题