如何在 Android 中使用 SQLite?

Posted

技术标签:

【中文标题】如何在 Android 中使用 SQLite?【英文标题】:How do I use SQLite in android? 【发布时间】:2016-01-13 23:51:16 【问题描述】:

我已经找到了一些关于这个主题的答案(例如this),但它不起作用。我只收到警告,它无法解析方法“openOrCreateDatabase(java.lang.String, int, null)”。

这是我的源代码:

public class DBHandler

    SQLiteDatabase database;
    DBHandler()
    
        database = openOrCreateDatabase("DatabaseName", Context.MODE_PRIVATE, null);
    

【问题讨论】:

试过official examples? 试试这个:vogella.com/tutorials/androidSQLite/article.html 【参考方案1】:

这是 SQLite 数据库和基本查询的完整代码。

public class SqliteHelper extends SQLiteOpenHelper 

    private SQLiteDatabase db;
    private Context mContext;

    public static final String DATABASE_NAME = "DemoDB";
    public static final int DATABASE_VERSION = 1;
    public static final String TABLE_USERS = "users";
    public static final String USER_ID = "id";
    public static final String USER_NAME = "username";
    public static final String USER_EMAIL = "email";
    public static final String USER_PASSWORD = "password";

    public static final String CREATE_QUERY_USER_TABLE = " CREATE TABLE " + TABLE_USERS
            + " ( "
            + USER_ID + " INTEGER PRIMARY KEY, "
            + USER_NAME + " TEXT, "
            + USER_EMAIL + " TEXT, "
            + USER_PASSWORD + " TEXT"
            + " ) ";

    public SqliteHelper(@Nullable Context context) 
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mContext = context;
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL(CREATE_QUERY_USER_TABLE);
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        db.execSQL(" DROP TABLE IF EXISTS " + TABLE_USERS);
    

    // Method to openthe Database
    public void openDataBase() throws SQLException 
        db = getWritableDatabase();
    

    // Method to close the Database
    public void close() 
        if (db != null && db.isOpen()) 
            db.close();
        
    

    public boolean isEmailExists(String email) 
        boolean isUserFound = false;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM users WHERE email = ?", new String[]email.trim());
        if (cursor != null) 
             if(cursor.getCount() > 0) 
                 isUserFound = true;
             
            cursor.close();
        

         return isUserFound;
    

    public void addUser(User user) 
        ContentValues values = new ContentValues();
        values.put(USER_NAME, user.userName);
        values.put(USER_EMAIL, user.email);
        values.put(USER_PASSWORD, user.password);

        long todo_id = db.insert(TABLE_USERS, null, values);
    

    public boolean login(User user) 
        boolean isLogin = false;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM users WHERE email = ?", new String[]user.email.trim());
        if (cursor != null) 
            if (cursor.getCount() > 0 && cursor.moveToFirst()) 
                String pass = cursor.getString(cursor.getColumnIndex(USER_PASSWORD));
                if (pass != null && user.password.equalsIgnoreCase(pass.trim())) 
                    isLogin = true;
                
            
            cursor.close();
        
        return isLogin;
    

【讨论】:

您好,欢迎来到 SO!虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。请阅读tour和How do I write a good answer?【参考方案2】:

创建“数据库”名称包并包含它

创建 SQLitHelper 名称类

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class SQLitHelper extends SQLiteOpenHelper 
    public static final String DataBase_Name = "ABC";
    public static final int Version = 1;
    public static final String TblUser = "TblUser";
    public static final String TblClassList = "TblClassList";
    public static final String TblStudentList = "TblStudentList";

    public SQLitHelper(Context context) 
        super(context, DataBase_Name, null, Version);
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL("Create table " + TblUser +
                "(id INTEGER PRIMARY KEY," +
                "uid INTEGER," +
                "fname TEXT," +
                "lname TEXT," +
                "email TEXT," +
                "password TEXT," +
                "teacher TEXT," +
                "student TEXT," +
                "parent TEXT," +
                "status TEXT," +
                "landing_page TEXT," +
                "createdate TEXT," +
                "birthdate TEXT," +
                "profilepic TEXT," +
                "phone TEXT," +
                "address TEXT," +
                "gender TEXT," +
                "age TEXT," +
                "googleid TEXT," +
                "facebookid TEXT," +
                "alert_time TEXT," +
                "sch_name TEXT,"+
                "login_with TEXT,"+
                "default_zone TEXT)");

        db.execSQL("Create table " + TblClassList +
                "(id INTEGER PRIMARY KEY," +
                "cid INTEGER," +
                "uid INTEGER," +
                "title TEXT," +
                "color TEXT," +
                "startdate TEXT," +
                "enddate TEXT," +
                "qrcode TEXT," +
                "createdate TEXT," +
                "not_submitted_count TEXT," +
                "status TEXT," +
                "extra1 TEXT," +
                "extra2 TEXT)");

        db.execSQL("Create table " + TblStudentList +
                "(id INTEGER PRIMARY KEY," +
                "uid INTEGER," +
                "cid INTEGER," +
                "fname TEXT," +
                "lname TEXT," +
                "email TEXT," +
                "profilepic TEXT," +
                "student_name TEXT," +
                "isleader TEXT," +
                "add_homework TEXT," +
                "track_submission TEXT," +
                "status TEXT," +
                "edit_homework TEXT," +
                "del_homework TEXT," +
                "last_access TEXT)");
    


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    


创建 DataHelper 类

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;

public class DataHelper 
    SQLitHelper sqLitHelper;
    SQLiteDatabase sqLiteDatabase;
    Context context;
    final String TAG = "DataHelper";

    public DataHelper(Context context) 
        sqLitHelper = new SQLitHelper(context);
        this.context = context;
        sqLiteDatabase = sqLitHelper.getWritableDatabase();
    


 public void open() 
        try 
            sqLiteDatabase = sqLitHelper.getWritableDatabase();
         catch (Exception e) 
            e.printStackTrace();
        
    

    public void close() 
        try 
            sqLiteDatabase.close();
         catch (Exception e) 
            e.printStackTrace();
        
    

    public void insertUser(HashMap<String, String> list) 
        ContentValues values = new ContentValues();
        open();
        try 
            for (String str : list.keySet())
                values.put(str, list.get(str));
            long rowId = sqLiteDatabase.insert(SQLitHelper.TblUser, null, values);
         catch (Exception e) 
            Log.e(TAG, "insertUser " + e.toString());
         finally 
            close();
        
    

    public void updateUser(HashMap<String, String> list, int uid) 
        ContentValues values = new ContentValues();
        open();
        try 
            for (String str : list.keySet())
                values.put(str, list.get(str));
            long rows = sqLiteDatabase.update(SQLitHelper.TblUser, values, "uid=" + uid, null);
         catch (Exception e) 
            Log.e(TAG, "insertUser " + e.toString());
         finally 
            close();
        
    

    public int getUserRecordCount() 
        int count = 0;
        try 
            open();
            Cursor cursor = sqLiteDatabase.rawQuery("Select * from " + SQLitHelper.TblUser, null);
            count = cursor.getCount();
            cursor.close();
         catch (Exception e) 
            Logger.debugLog(TAG, "userCount : " + e.toString());
         finally 
            close();
        
        return count;
    


    public HashMap<String,String> getUserDetail()
        HashMap<String, String> list = new HashMap<>();
        Cursor cursor = null;
        try 
            open();
            cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + SQLitHelper.TblUser, null);
            if (cursor.getColumnCount() > 0) 
                while (cursor.moveToNext()) 

                    list.put("uid", cursor.getString(cursor.getColumnIndex("uid")));
                    list.put("fname", cursor.getString(cursor.getColumnIndex("fname")));
                    list.put("lname", cursor.getString(cursor.getColumnIndex("lname")));
                    list.put("default_zone", cursor.getString(cursor.getColumnIndex("default_zone")));
                    list.put("teacher", cursor.getString(cursor.getColumnIndex("teacher")));
                    list.put("student", cursor.getString(cursor.getColumnIndex("student")));
                    list.put("parent", cursor.getString(cursor.getColumnIndex("parent")));
                    list.put("email", cursor.getString(cursor.getColumnIndex("email")));
                    list.put("gender", cursor.getString(cursor.getColumnIndex("gender")));
                    list.put("birthdate", cursor.getString(cursor.getColumnIndex("birthdate")));
                    list.put("profilepic", cursor.getString(cursor.getColumnIndex("profilepic")));
                    list.put("sch_name", cursor.getString(cursor.getColumnIndex("sch_name")));
                    list.put("login_with", cursor.getString(cursor.getColumnIndex("login_with")));

                
            
         catch (Exception e) 
            Logger.debugLog(TAG, "getUserDetail : " + e.toString());
         finally 
            close();
            if (cursor != null)
                if (!cursor.isClosed())
                    cursor.close();
        
        return list;
    

    public boolean deleteUserList() 
        try 
            open();
            if (sqLiteDatabase.delete(SQLitHelper.TblUser, null, null) > 0)
                return true;
            else 
                return false;
            
         catch (Exception e) 
            Logger.debugLog(TAG, "deleteUserList : " + e.toString());
         finally 
            close();
        
        return false;
    


    public boolean insertClassList(MClassList mClassList) 
        try 
            open();
            ContentValues contentValues = new ContentValues();
            contentValues.put("cid", mClassList.getId());
            contentValues.put("uid", mClassList.getUid());
            contentValues.put("title", mClassList.getTitle());
            contentValues.put("color", mClassList.getColor());
            contentValues.put("startdate", mClassList.getStartdate());
            contentValues.put("enddate", mClassList.getEnddate());
            contentValues.put("qrcode", mClassList.getQrcode());
            contentValues.put("createdate", mClassList.getCreatedate());
            contentValues.put("status", mClassList.getStatus());
            contentValues.put("not_submitted_count", mClassList.getNot_sub_count());
            long id = sqLiteDatabase.insert(SQLitHelper.TblClassList, null, contentValues);
            Logger.debugLog(TAG, "insertClassList : Sus");
            return true;
         catch (Exception e) 
            Logger.debugLog(TAG, "insertClassList : " + e.toString());
         finally 
            close();
        
        return false;
    

    public ArrayList<MClassList> getClassList() 
        ArrayList<MClassList> clssArrayList = new ArrayList<>();
        Cursor cursor = null;
        try 
            open();
            String Query = QueryBuilder.classListQuery();
            cursor = sqLiteDatabase.rawQuery(Query, null);
            if (cursor.getColumnCount() > 0) 
                while (cursor.moveToNext()) 
                    MClassList mClassList = new MClassList();

                    mClassList.setId(cursor.getInt(cursor.getColumnIndex("cid")));
                    mClassList.setUid(cursor.getInt(cursor.getColumnIndex("uid")));
                    mClassList.setTitle(cursor.getString(cursor.getColumnIndex("title")));
                    mClassList.setColor(cursor.getString(cursor.getColumnIndex("color")));
                    mClassList.setStartdate(cursor.getString(cursor.getColumnIndex("startdate")));
                    mClassList.setEnddate(cursor.getString(cursor.getColumnIndex("enddate")));
                    mClassList.setQrcode(cursor.getString(cursor.getColumnIndex("qrcode")));
                    mClassList.setCreatedate(cursor.getString(cursor.getColumnIndex("createdate")));
                    mClassList.setStatus(cursor.getString(cursor.getColumnIndex("status")));
                    mClassList.setNot_sub_count(cursor.getString(cursor.getColumnIndex("not_submitted_count")));

                    clssArrayList.add(mClassList);
                
            
         catch (Exception e) 
            Logger.debugLog(TAG, "getClassList : " + e.toString());
         finally 
            close();
            if (cursor != null)
                if (!cursor.isClosed())
                    cursor.close();
        
        return clssArrayList;
    

    public boolean deleteClassList() 
        try 
            open();
            if (sqLiteDatabase.delete(SQLitHelper.TblClassList, null, null) > 0)
                return true;
            else 
                return false;
            

         catch (Exception e) 
            Logger.debugLog(TAG, "deleteClassList : " + e.toString());
         finally 
            close();
        
        return false;
    

    public boolean deleteStudentList() 
        try 
            open();
            if (sqLiteDatabase.delete(SQLitHelper.TblStudentList, null, null) > 0)
                return true;
            
            else
                return false;
            

         catch (Exception e) 
            Logger.debugLog(TAG, "deleteStudentList : " + e.toString());
         finally 
            close();
        
        return false;
    

   public void deleteStudent(int cid,int uid) 
        try 
            open();
            sqLiteDatabase.delete(SQLitHelper.TblStudentList, "uid=" + uid + " AND cid=" + cid, null);
         catch (Exception e) 
            Logger.debugLog(TAG, "deleteStudent : " + e.toString());
         finally 
            close();
        
    


创建类 QueryBuilder

public class QueryBuilder 

    public static String teacherABCList(int cid) 
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = df.format(c.getTime()).toString();

        String Query = "SELECT * FROM " + SQLitHelper.TblTeacherHomeworkAll + " WHERE cid='" + cid + "'" + " AND duedate>= " +"'"+ formatDate+"'" + " ORDER BY duedate DESC ";
        return Query;
    

==============================

  public static String studentXXXListQuery(int uid,String status) 
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String formatDate = df.format(c.getTime()).toString();


        String Query = "SELECT * FROM " + SQLitHelper.TblStudentHomeworkAll + " WHERE uid='" + uid + "'" + " AND status= " +"'"+ status+"'"+" AND isDone='N'" + " ORDER BY duedate DESC ";
        return Query;
    

===========================================

 public static String studentListQuery(String questionID) 
        String query = "SELECT * FROM " + SQLitHelper.TblStudentCheckAnswer + " WHERE qid=" + questionID;
        return query;
    


【讨论】:

【参考方案3】:

这是我的代码如何使用 sqlite 数据库

DatabaseHelper.java

            public class DatabaseHelper extends SQLiteOpenHelper 

                    public DatabaseHelper(Context context) 
                        super(context, "loginDB.db", null, 1);
                        getWritableDatabase();
                    

                    @Override
                    public void onCreate(SQLiteDatabase sqLiteDatabase) 
                        String query = "create table registration (id INTEGER,Image BLOB,firstname VARCHAR,Lastname VARCHAR,DateOfBirth VARCHAR,Phone VARCHAR,Gender VARCHAR, Email VARCHAR primary key,Password VARCHAR);";
                        sqLiteDatabase.execSQL(query);
                    

                    @Override
                    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) 

                    
            //method for insert data
            public boolean insertRecord(byte[] imageInByte,String fn) 
                SQLiteDatabase db = this.getWritableDatabase();
                ContentValues contentValues = new ContentValues();
                contentValues.put("Image", imageInByte);
                contentValues.put("Firstname", fn);
                db.insert("signup", null, contentValues);
                return true;
            

       public boolean updaterecord(String fn,String ln,String unme)
                SQLiteDatabase db = this.getWritableDatabase();
                ContentValues contentValues = new ContentValues();
                contentValues.put("Firstname", fn);
                contentValues.put("Lastname", ln);
                contentValues.put("Username", unme);
                return db.update(TABLE_NAME, contentValues, "Username = ?", new String[](unme)) > 0;
            

public boolean deleterecord(String FirstName) 

            SQLiteDatabase db = this.getWritableDatabase();
            return db.delete(TABLE_NAME, "Firstname = ?", new String[]FirstName) > 0;
        

             public int displayDetail(String email, String password) 
                    SQLiteDatabase db = this.getWritableDatabase();
                    Cursor cursor = db.rawQuery("select * from registration where Email='" + email + "'AND Password='" + password + "'", null);

                    return cursor.getCount();
                

                public ArrayList displayDetails(String email, String password) 
                    SQLiteDatabase db = this.getWritableDatabase();
                    Cursor cursor = db.rawQuery("select * from registration where Email='" + email + "'AND Password='" + password + "'", null);

                    ArrayList<ModelClass> arrayList = new ArrayList();
                    ModelClass model;
                    if (cursor != null) 
                        if (cursor.getCount() > 0) 
                            while (cursor.moveToNext()) 
                                model = new Model();
                                model.setFirstname(cursor.getString(cursor.getColumnIndex("Firstname")));
                                model.setLastname(cursor.getString(cursor.getColumnIndex("Lastname")));
                                arrayList.add(model);
                            
                        
                    
                    return arrayList;
                
                

【讨论】:

【参考方案4】:

将数据保存到sqlite中,首先在main中使用

public class MainActivity extends AppCompatActivity 

String one,two;
EditText name,phone;
Button saveButton;
List<StudentModel> list = new ArrayList<StudentModel>();
DatabaseHelper db;
@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    db = new DatabaseHelper(getApplicationContext());

    saveButton=(Button)findViewById(R.id.submit);
    name=(EditText)findViewById(R.id.textName);
    phone=(EditText)findViewById(R.id.textPhone);

    saveButton.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 

            StudentModel student = new StudentModel();
            student.name = name.getText().toString();
            student.phone_number = phone.getText().toString();
            db.addStudentDetail(student);

            list = db.getAllStudentsList();
            print(list);




        
    );

private void print(List<StudentModel> list) 

    String value = "";
    for(StudentModel sm : list)
        value = value+"id: "+sm.id+", name: "+sm.name+" Ph_no: "+sm.phone_number+"\n";
    

    Log.i("<<<<<<<<<<",value);





然后创建处理程序类

public class DatabaseHelper extends SQLiteOpenHelper 

// Database Name
public static String DATABASE_NAME = "student_database";


private static final int DATABASE_VERSION = 1;


private static final String TABLE_STUDENTS = "students";


private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PHONENUMBER = "phone_number";

public static String TAG = "tag";



private static final String CREATE_TABLE_STUDENTS = "CREATE TABLE "
        + TABLE_STUDENTS + "(" + KEY_ID
        + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT,"
        + KEY_PHONENUMBER + " TEXT );";

public DatabaseHelper(Context context) 
    super(context, DATABASE_NAME, null, DATABASE_VERSION);



@Override
public void onCreate(SQLiteDatabase db) 

    db.execSQL(CREATE_TABLE_STUDENTS); 




@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_STUDENTS);

    onCreate(db);



public long addStudentDetail(StudentModel student) 
    SQLiteDatabase db = this.getWritableDatabase();

    // Creating content values
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, student.name);
    values.put(KEY_PHONENUMBER, student.phone_number);

    // insert row in students table

    long insert = db.insert(TABLE_STUDENTS, null, values);

    return insert;



public int updateEntry(StudentModel student) 
    SQLiteDatabase db = this.getWritableDatabase();

    // Creating content values
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, student.name);
    values.put(KEY_PHONENUMBER, student.phone_number);

    return db.update(TABLE_STUDENTS, values, KEY_ID + " = ?",
            new String[]  String.valueOf(student.id) );



public void deleteEntry(long id) 

    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_STUDENTS, KEY_ID + " = ?",
            new String[]  String.valueOf(id) );


public StudentModel getStudent(long id) 
    SQLiteDatabase db = this.getReadableDatabase();


    String selectQuery = "SELECT  * FROM " + TABLE_STUDENTS + " WHERE "
            + KEY_ID + " = " + id;
    Log.d(TAG, selectQuery);

    Cursor c = db.rawQuery(selectQuery, null);

    if (c != null)
        c.moveToFirst();

    StudentModel students = new StudentModel();
    students.id = c.getInt(c.getColumnIndex(KEY_ID));
    students.phone_number = c.getString(c.getColumnIndex(KEY_PHONENUMBER));
    students.name = c.getString(c.getColumnIndex(KEY_NAME));

    return students;



public List<StudentModel> getAllStudentsList() 
    List<StudentModel> studentsArrayList = new ArrayList<StudentModel>();

    String selectQuery = "SELECT  * FROM " + TABLE_STUDENTS;
    Log.d(TAG, selectQuery);

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor c = db.rawQuery(selectQuery, null);


    if (c.moveToFirst()) 
        do 

            StudentModel students = new StudentModel();
            students.id = c.getInt(c.getColumnIndex(KEY_ID));
            students.phone_number = c.getString(c
                    .getColumnIndex(KEY_PHONENUMBER));
            students.name = c.getString(c.getColumnIndex(KEY_NAME));


            studentsArrayList.add(students);
         while (c.moveToNext());
    

    return studentsArrayList;


然后设置并获取值

public class StudentModel 

public int id;
public String name;
public String phone_number;

public StudentModel(int id, String name, String phone_number) 
    // TODO Auto-generated constructor stub
    this.id = id;
    this.name = name;
    this.phone_number = phone_number;

public StudentModel()



试试看

【讨论】:

【参考方案5】:

使用以下示例创建数据库

 import android.content.ContentValues;
        import android.content.Context;
        import android.database.sqlite.SQLiteDatabase;
        import android.database.sqlite.SQLiteOpenHelper;
        import android.util.Log;

        import com.ayconsultancy.sumeshmedicals.SumeshMedicalContext;
        import com.ayconsultancy.sumeshmedicals.model.PlaceModel;
        import com.ayconsultancy.sumeshmedicals.utils.Utils;

        import org.json.JSONArray;
        import org.json.JSONException;
        import org.json.JSONObject;

        import java.util.ArrayList;

        /**
         * Created by Admin33 on 16-02-2016.
         */
        public class DBHelper extends SQLiteOpenHelper 
            static String DATABASE_NAME = "sumesh_medicals";
            static int DATABASE_VERSION = 1;
            static DBHelper dbHelperInstance;
            static SQLiteDatabase db;

            public DBHelper(Context context) 
                super(context, DATABASE_NAME, null, DATABASE_VERSION);
            

            public static DBHelper getInstance() 
                if (dbHelperInstance == null) 
                    dbHelperInstance = new DBHelper(SumeshMedicalContext.getContext());
                
                return dbHelperInstance;
            

            @Override
            public void onCreate(SQLiteDatabase db) 
                Utils.ShowLogD("in sqlite oncreate");
                try 
                    db.execSQL(DBQueries.CREATE_OTC_TABLE);
                    db.execSQL(DBQueries.CREATE_SHOP_DETAILS_TABLE);
                    db.execSQL(DBQueries.CREATE_USER_DETAILS_TABLE);
                    db.execSQL(DBQueries.CREATE_CITY_TABLE);
                 catch (Exception e) 
                    e.printStackTrace();
                

               // insertIntoShopDetails(db);
                //  insertIntoOTcPrescrion(db);

            

            public synchronized SQLiteDatabase getDababase() 
                if (db == null || (db != null && !db.isOpen())) 
                    db = this.getWritableDatabase();
                
                return db;
            

            public synchronized void close() 
                super.close();
                if (db != null)
                    db.close();
            

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 

            

【讨论】:

【参考方案6】:

正如评论者给您的示例一样,您需要创建 SQLiteOpenHelper 类的子类并覆盖将创建数据库和表的 onCreate 和 onUpgrade 方法。然后你可以使用这个帮助类的方法 getReadableDatabase( )getWritableDatabase( ) 来获取 SQLite 数据库的副本。您可以对此对象执行查询。 下面的代码 sn-p 演示了它。

public class DBAdapter 
private SQLiteDatabase database;
private Context context;
private DatabaseHelper dbHelper;


private class DatabaseHelper extends SQLiteOpenHelper 

    public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) 
        super(context, name, factory, version);
    

    @Override
    public void onCreate(SQLiteDatabase db) 
        db.execSQL(CREATE_TABLES_QUERY);
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        db.execSQL("DROP TABLE IF EXIST "+TABLE_QUERY);
    


public DBAdapter(Context ctx) 
    this.context = ctx;



public DBAdapter open() throws SQLException 
    dbHelper = new DatabaseHelper(context, DBNAME, null,DBVERSION);
    database = dbHelper.getWritableDatabase();
    return this;


public Cursor executeQuery() 
    Cursor result = database.rawQuery(YOUR_QUERY, null);
    return result;

使用SQLite Open Helper developers guide 获取更多帮助。

希望对你有帮助。

【讨论】:

【参考方案7】:
public class Sqlhelper extends SQLiteOpenHelper 
private SQLiteDatabase db;
public static final String KEY_ROWID = "_id";
public static final String KEY_FNAME = "firstname";

Sqlhelper DB = null;
private static final String DATABASE_NAME = "dbname.db";
private static final int DATABASE_VERSION = 2;
public static final String DATABASE_TABLE_NAME = "db";

private static final String DATABASE_TABLE_CREATE =
        "CREATE TABLE " + DATABASE_TABLE_NAME + "(" +
                "_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
                "firstname TEXT NOT NULL);";



public Sqlhelper(Context context) 
    super(context, DATABASE_NAME, null, DATABASE_VERSION);


@Override
public void onCreate(SQLiteDatabase db) 
    try

        db.execSQL(DATABASE_TABLE_CREATE);
        Log.d("DATABASE", "Table Was Created");


    catch(Exception e)
        e.printStackTrace();
    



public void open() 

    getWritableDatabase();



@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 

    onCreate(db);
    Log.d("DATABASE", "Table Was UPDATED");


【讨论】:

太好了,这肯定会帮助他了解 Android 中的 SQL 数据库是如何工作的...... -1【参考方案8】:

SQLite 是一个开源 SQL 数据库,可将数据存储到设备上的文本文件中。 Android 带有内置的 SQLite 数据库实现。

请查看以下链接

    Android SQLite Database Tutorial

    SQLite Database Tutorial

    SQLite and Android

结构

 public class mysqliteHelper extends SQLiteOpenHelper 

  public static final String TABLE_COMMENTS = "comments";
  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_COMMENT = "comment";

  private static final String DATABASE_NAME = "commments.db";
  private static final int DATABASE_VERSION = 1;

  // Database creation sql statement
  private static final String DATABASE_CREATE = "create table "
      + TABLE_COMMENTS + "(" + COLUMN_ID
      + " integer primary key autoincrement, " + COLUMN_COMMENT
      + " text not null);";

  public MySQLiteHelper(Context context) 
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
  

  @Override
  public void onCreate(SQLiteDatabase database) 
    database.execSQL(DATABASE_CREATE);
  

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    Log.w(MySQLiteHelper.class.getName(),
        "Upgrading database from version " + oldVersion + " to "
            + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_COMMENTS);
    onCreate(db);
  

 

【讨论】:

以上是关于如何在 Android 中使用 SQLite?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Android 中使用 SQLite?

如何在 SQLite 查询中忽略重音(Android)

如何使用 SQLite 在 Android 中获取查询的行数?

如何在我的 Android 程序的 SQLite Manager 应用程序中使用我创建的 SQLite DB

如何使用 Qt 在 Android 中读取现有的 SQLite 数据库?

如何在 android studio 中使用 sqlite 为特定帐户创建表?