在android中建立sqlite连接的最佳方法是什么?

时间:2014-10-21 02:44:13

标签: android sqlite

我见过很多与sqlite连接有关的例子。但是我还没有找到任何正确的代码。有谁请说明一步一步的sqlite连接过程与所有可能性?

4 个答案:

答案 0 :(得分:2)

  1. 首先,您需要创建一个数据库。 您可以通过创建扩展SQLiteOpenHelper的DatabaseHelper类来完成此操作。 覆盖onCreate()和onUpgrade()方法:

    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);
        }
    }
    
  2. 当您的应用首次启动时,Android操作系统会调用您的onCreate()方法来创建数据库和您的表。

    1. 创建MyTable类。

      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);
          }
      }
      
    2. 在这里创建表并进行升级。创建一个Contract类的委托。将所有列活动提取到Contract类中是一种很好的做法。升级,在大多数情况下,删除并重新创建表是可以的,除非您想保留一些像Login这样的数据。

      1. 创建表合约。

        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;
        }
        
      2. 您可以在此处指定要创建的列以及查询数据库时要返回的列。

        1. 插入/查询。 然后,无论您想要插入/查询数据库,都可以执行以下操作:

          // 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();
          

答案 1 :(得分:0)

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

答案 2 :(得分:0)

 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 });

}

}

答案 3 :(得分:0)

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;
    }

    }