삽입 후 생성 된 아이디 얻기
Android에서 SQLite를 사용하고 있으며 삽입 된 행의 생성 된 ID를 얻는 가장 좋은 방법을 알고 싶습니다.
내가 생각한 솔루션은 포함 후 검색하지만 가장 좋은 방법은 아닙니다.
이 insert
메소드는 id
방금 삽입 된 행 또는 -1
삽입 중 오류가있는 경우 of of row를 리턴합니다 .
long id = db.insert(...);
여기서 db는 SQLiteDatabase
입니다.
ContentValues를 사용하는 경우 :
DBHelper db =new DBHelper();// your dbHelper
ContentValues values = new ContentValues();
values.put("firstName","Ahmad");
values.put("lastName","Aghazadeh");
long insertedId= db.getSQLiteDatabase().insert("user", "", values) ;
쿼리 실행자가 사용하는 경우 select last_insert_rowid()
String sql = "INSERT INTO [user](firstName,lastName) VALUES (\"Ahmad\",\"Aghazadeh\"); select last_insert_rowid()";
DBHelper itemType =new DBHelper();// your dbHelper
c = db.rawQuery(sql, null);
if (c.moveToFirst())
result = c.getLong(0);
방을 사용하는 경우
@Entity
class User {
@PrimaryKey(autoGenerate = true)
public int id;
//...
}
@Dao
public interface UserDao{
@Insert(onConflict = OnConflictStrategy.REPLACE)
long insert(User user);
// Insert multiple users
@Insert(onConflict = OnConflictStrategy.REPLACE)
long[] insert(User... user);
}
나는 소스를 확인했다. insert
메소드 사용 sqlite3_last_insert_rowid
함수는 id를 반환합니다. 설명서에 따르면 https://www.sqlite.org/c3ref/last_insert_rowid.html 행 ID는 숨겨진 열이거나 INTEGER PRIMARY KEY
선언 된 경우 유형의 열입니다 .
이것이 기본 _ID
열입니다.
mySQL 에서이 문제에 대해 약간의 문제가 있었지만 LAST_INSERT_ID는 ID를 얻는 신뢰할 수있는 방법이 아닙니다. 데이터베이스를 망치는 사용자가있는 경우 반환 된 ID는 실행 한 쿼리에 의해 삽입 된 ID가 아닐 수 있습니다. 다른 사용자는이 ID의 반환에 영향을 줄 수 있습니다. 우리는 1 분 안에 평균 7000 명의 사용자를 가진 서버를 가지고 있었고 항상 우연히 발견되었습니다.
우리가 해결 한 솔루션은 삽입 한 쿼리의 데이터를 사용한 다음 해당 데이터를 사용하여 해당 결과를 검색하는 것입니다. 어쨌든 마지막 ID를 찾는 요청을하고 있습니다. 따라서 id를 얻기 위해 field = var 및 field = var 인 SELECT id FROM 테이블을 수행 할 수도 있습니다. 쿼리에서 약간의 성능 저하가 있었지만 훨씬 더 안정적인 결과가 반환되었습니다.
을 사용하여 마지막으로 삽입 된 행 _id를 얻을 수 있습니다 last_insert_rowid()
. 샘플 코드는 다음과 같습니다.
/**
* Return Last inserted row id(auto incremented row) (_id)
* @return
*/
public int getLastAddedRowId() {
String queryLastRowInserted = "select last_insert_rowid()";
final Cursor cursor = database.rawQuery(queryLastRowInserted, null);
int _idLastInsertedRow = 0;
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
_idLastInsertedRow = cursor.getInt(0);
}
} finally {
cursor.close();
}
}
return _idLastInsertedRow;
}
참고URL : https://stackoverflow.com/questions/5409751/get-generated-id-after-insert
'Programming' 카테고리의 다른 글
java.lang.IllegalStateException : 단편이 활동에 첨부되지 않음 (0) | 2020.06.27 |
---|---|
경고 : refname 'HEAD'가 모호합니다. (0) | 2020.06.27 |
jQuery UI 대화 상자를 ajax 가로 드 한 내용의 너비로 자동 크기 조정 (0) | 2020.06.27 |
한 SQLite 데이터베이스에서 다른 SQLite 데이터베이스로 데이터 복사 (0) | 2020.06.27 |
데이터 프레임에서 그룹 내 행 번호 매기기 (0) | 2020.06.27 |