Android 학습 노트-SQL 데이터베이스 에 데 이 터 를 저장(SQL Databases 에 데이터 저장)
1.SQL Helper 로 데이터베이스 만 들 기
2.데이터 의 첨삭 수정(PRDU:Put,Read,Delete,Update)
배경 지식:
지난 글 에서 배 웠 습 니 다android 파일 저장오늘 배 운 것 은 데 이 터 를 SQL 데이터베이스 에 저장 하 는 것 입 니 다.모두 가 데이터베이스 에 대해 낯 설 지 않 을 것 이 라 고 믿는다.대량의 중복 되 고 특정한 구조 가 있 는 데이터 의 저장 은 SQL 데이터베이스 로 저장 하 는 것 이 가장 이상 적 이다.
다음은 연락처 에 관 한 데이터베이스 데모 로 구체 적 으로 공부 하 겠 습 니 다.
구체 적 인 지식:
1.Contract 클래스 정의
SQL 데이터 베 이 스 를 만 들 기 전에 Contract 클래스 를 만 듭 니 다.그럼 Contract 류 가 뭐 죠?
Contract Class :
Contract Class, Companion Class。
Android Developer :
< A contract class is a container for constants that define names for URIs,
tables, and columns. The contract class allows you to use the same constants
across all the other classes in the same package. This lets you change a
column name in one place and have it propagate throughout your code.>
Contact URI、 、 。 。
, 。
package com.example.sqlitetest;
//Contract
public class Contact {
int _id;
String _name;
String _phone_number;
public Contact(){
}
public Contact(int id, String name, String _phone_number){
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
public Contact(String name, String _phone_number){
this._name = name;
this._phone_number = _phone_number;
}
public int getID(){
return this._id;
}
public void setID(int id){
this._id = id;
}
public String getName(){
return this._name;
}
public void setName(String name){
this._name = name;
}
public String getPhoneNumber(){
return this._phone_number;
}
public void setPhoneNumber(String phone_number){
this._phone_number = phone_number;
}
}
2.SQLHelper 로 데이터베이스 만 들 기파일 을 내부 에 저장 하 는 것 처럼 안 드 로 이 드 는 개인 적 인 응용 저장 공간 에 우리 의 데이터 베 이 스 를 저장 하면 우리 의 데이터 가 안전 하 다 는 것 을 보장 합 니 다.다른 응용 프로그램 에 접근 할 수 없습니다.
장치 에 저 장 된 데이터베이스 저장:
/data/data/
SQLiteOpenHelper 를 사용 하기 위해 서 는 onCreate(),onUpgrade(),onOpen()리 셋 방법 을 다시 쓴 하위 클래스 를 만들어 야 합 니 다.
3.데이터 의 첨삭 검사
증가:ContentValue 값 을 insert()방법 으로 전달 합 니 다.
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
db.insert(TABLE_CONTACTS, null, values);
db.close();
삭제:delete()방법
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
개정:update()방법
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
ew String[] { String.valueOf(contact.getID()) });
검색:query()방법
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return contact;
전체 DatabaseHelper 코드 는 다음 과 같 습 니 다.
package com.example.sqlitetest;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
//
private static final int DATABASE_VERSION = 1;
//
private static final String DATABASE_NAME = "contactsManager";
//Contact
private static final String TABLE_CONTACTS = "contacts";
//Contact
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
//
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
//
onCreate(db);
}
/**
*
*/
//
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
//
db.insert(TABLE_CONTACTS, null, values);
db.close(); //
}
//
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return contact;
}
//
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
} while (cursor.moveToNext());
}
return contactList;
}
//
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
//
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
//
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
//
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}
이번 학습 의 중점 이 아니 라 붙 이지 않 는 코드 도 있다.필요 한 댓 글 이 있 으 면 찾 아 주세요.데모 실행 효과 도:
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Bitrise에서 배포 어플리케이션 설정 테스트하기이 글은 Bitrise 광고 달력의 23일째 글입니다. 자체 또는 당사 등에서 Bitrise 구축 서비스를 사용합니다. 그나저나 며칠 전 Bitrise User Group Meetup #3에서 아래 슬라이드를 발표했...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.