简体   繁体   中英

What is the best way to establish sqlite connection in android?

I have seen lots of examples related sqlite connection. But there is no any proper code I have still found. Anyone please describe step by step sqlite connection process with all possibilities ?

  1. First, you need to create a database. You do this by creating a DatabaseHelper class that extends SQLiteOpenHelper. Override the onCreate() and onUpgrade() methods:

     public class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, Config.DATABASE_NAME, null, Config.DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { MyTable.onCreate(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { MyTable.onUpgrade(db, oldVersion, newVersion); } } 

When your app starts for the first time, Android OS will call your onCreate() method to create the database and your table.

  1. Create MyTable class.

     public class MyTable { // Database table public static final String TABLE_NAME = "mytable"; // Create statement private static final String SQL_CREATE_MY_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + MyTableContract.SQL_CREATE_COLUMN_CLAUSE + ");"; public static void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_MY_TABLE); } public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } } 

Here you create the table and upgrade it. Create just delegates to a Contract class. It's a good practice to extract all column activity into a Contract class. Upgrade, in most cases it's ok to drop and re-create the table, unless you want to preserve some data like Login.

  1. Create your Table Contract.

     public class MyTableContract { // COLUMNS public static final String COLUMN_ID = "_id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_AGE = "age"; // Create clause public static final String SQL_CREATE_COLUMN_CLAUSE = COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT, " + COLUMN_AGE + " INTEGER"; // Query projection public static final String[] QUERY_PROJECTION = { COLUMN_ID, COLUMN_NAME, COLUMN_AGE }; // Selection clause - return all rows public static final String SELECTION_CLAUSE = null; // Selection arguments public static final String[] SELECTION_ARGS = null; // Use default sort order public static final String QUERY_SORT_ORDER = null; } 

This is where you specify which columns you want created and which columns you want returned when you query the database.

  1. Insert / Query. Then wherever you want to insert/query the database, you can do this:

     // Create a Database Helper private DatabaseHelper mDbHelper = new DatabaseHelper(getContext()); // Get the writable database to Insert SQLiteDatabase db = mDbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(MyTableContract.COLUMN_NAME, "eduard"); values.put(MyTableContract.COLUMN_AGE, 32); long insertId = database.insert(MyTable.TABLE_NAME, null, values); // Get the readable database to Query SQLiteDatabase db = mDbHelper.getReadableDatabase(); Cursor cursor = database.query(MyTable.TABLE_NAME, MyTableContract.QUERY_PROJECTION, MyTableContract.COLUMN_AGE + " = 32", null, null, null, null); cursor.moveToFirst(); String nameReturned = cursor.getString(0); cursor.close(); 

尝试创建两个不同的文件,一个用于数据库处理程序,另一个用于简单地编写查询。在数据库处理程序中将其扩展到SQLiteOpenhelper并实现方法。oncreate()方法根据您的要求创建数据库,而查询文件中的创建方法需要并在方法内部编写查询,然后在您的活动中调用它们的对象。

 public class Database_Helper {
   private Context context;
public static String DB_name = "demo.sqlite";
Demo_DBHelper dh;
SQLiteDatabase sdb;

private static class Demo_DBHelper extends SQLiteOpenHelper {

    public Demo_DBHelper(Context context) {

        super(context, DB_name, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        System.out.println("On Create Called");
        db.execSQL("Create TABLE IF NOT EXISTS Contact_Detail(mid INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR,phonenumber VARCHAR)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

        db.execSQL("DROP TABLE IF EXISTS Contact_Detail");

        // db.execSQL("DROP TABLE IF EXISTS CommunityDetails");
    }

}

public Database_Helper(Context c) {
    context = c;
}

public Database_Helper Open() throws SQLiteException {
    dh = new Demo_DBHelper(context);
    sdb = dh.getWritableDatabase();
    return this;
}

public void close() {
    dh.close();
}

public void clearData() {
    sdb.execSQL("DROP TABLE IF EXISTS Contact_Detail");

}

public Cursor getContactDetail() {

    String st = "SELECT * from Contact_Detail";

    Cursor rs_message = sdb.rawQuery(st, null);
    return rs_message;

}

public void add_contact(String name, String phonenumber) {

    ContentValues cv = new ContentValues();
    cv.put("name", name);
    cv.put("phonenumber", phonenumber);
    sdb.insert("Contact_Detail", null, cv);

}

public void removephone(int phonenumber) {

    String str = "SELECT * FROM Contact_Detail where phonenumber='"
            + phonenumber + "' ";
    Cursor rs_message = sdb.rawQuery(str, null);
    if (rs_message.moveToFirst()) {

        String st = "DELETE FROM Contact_Detail where phonenumber='"
                + phonenumber + "' ";
        sdb.execSQL(st);
    }

}

public void update_contactdetail(String phonenumber, String name) {

    ContentValues cv = new ContentValues();
    cv.put("name", "" + name);

    sdb.update("Contact_Detail", cv, "phonenumber=?",
            new String[] { phonenumber });

}

}

public class DBAdapter {
    //User Master
    public static final String KEY_ROWID = "id";
    public static final String KEY_Email = "email";
    public static final String KEY_PASS = "pass";



    private static final String DATABASE_NAME = "TEST_DB";
    private static final int DATABASE_VIRSION = 1;

    private static final String DATABASE_CREATE = "create table User_Mst(id integer primary key,email text,pass text);";

    private Context context = null;
    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter(Context con) {
    this.context = con;
    DBHelper = new DatabaseHelper(context);
    }
    private class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
    // TODO Auto-generated constructor stub
    super(context, DATABASE_NAME, null, DATABASE_VIRSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    try {
    db.execSQL(DATABASE_CREATE);


    } catch (SQLException e) {
    e.printStackTrace();
    }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

    db.execSQL("DROP TABLE IF EXISTS User_Mst");



    onCreate(db);
    }
    }

    public DBAdapter open() throws SQLException {
    db = DBHelper.getWritableDatabase();
    return this;
    }
    public void close() {
    DBHelper.close();
    }
    public long insertuser(int i,String mail,String pass) {

    ContentValues init = new ContentValues();
    init.put(KEY_ROWID, i);
    init.put(KEY_Email, mail);
    init.put(KEY_PASS, pass);
    return db.insert("User_Mst", null, init);
    }




    public boolean deleteUser(long rowid) {
    return db.delete("User_Mst", KEY_ROWID + "=" + rowid, null) > 0;
    }



    public Cursor getuser() {
    return db.query("User_Mst", new String[] { KEY_ROWID,KEY_Email,
    KEY_PASS }, null, null, null, null, null);
    }





    public Cursor getUser(long rowid) throws SQLException {
    Cursor mycursor = db.query(true, "User_Mst", new String[] { KEY_ROWID,KEY_Email,KEY_PASS },
    KEY_ROWID + "=" + rowid, null, null,    null, null, null);
    if (mycursor != null) {
    mycursor.moveToFirst();
    }
    return mycursor;
    }

    public boolean updateuser(long rowid,String mail,String pass) {
    ContentValues args = new ContentValues();
    args.put(KEY_Email, mail);
    args.put(KEY_PASS,pass);
    return db.update("User_Mst", args, KEY_ROWID + "=" + rowid, null) > 0;
    }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM