简体   繁体   English

在Android中创建并连接到SQLite数据库

[英]Creating and connecting to an SQLite DB in Android

I am trying to create an SQLite Db for my android application, I have tried a lot of online tutorials and none of them work for me! 我正在尝试为我的android应用程序创建一个SQLite Db,我尝试了很多在线教程,但没有一个对我有用! I have posted my code below: 我在下面发布了我的代码:

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "usersManager";

    // Contacts table name
    private static final String TABLE_CONTACTS = "users";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);
    }



import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;


public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        DatabaseHandler db = new DatabaseHandler(this);

I cant see error in my code but when I check in the location were db should be created nothing is there. 我看不到我的代码中的错误,但是当我检查位置时应该创建db时什么也没有。

Apart from avoiding long one lined concatenated strings: 除了避免长的一行内联的字符串之外:

@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = 
            "CREATE TABLE " + TABLE_CONTACTS + 
            "(" + 
                KEY_ID   + " INTEGER PRIMARY KEY," + 
                KEY_NAME + " TEXT" + //--last value has no comma--
            ")";

    db.execSQL(CREATE_CONTACTS_TABLE);
}

Call getWritableDataBase() to open database, it will be created if it is not already there. 调用getWritableDataBase()打开数据库,如果尚未存在,则会创建该数据库。

Try this 尝试这个

public class DataBase extends SQLiteOpenHelper{


    static String createBDSQL = "CREATE TABLE Notas (id integer primary key autoincrement, title TEXT)";

    public DataBase(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(createBDSQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS Notas");
            db.execSQL(createBDSQL);
    }
}

In MainActivity.java 在MainActivity.java中

DataBase notasdb = new DataBase(this, "DBSample.db", null, 1);
SQLiteDatabase db = notasdb.getWritableDatabase();

The SQLiteOpenHelper is lazy. SQLiteOpenHelper是惰性的。 It will not perform any action until necessary. 除非必要,否则它不会执行任何操作。 Thus, your DB will only be created when you try to access data in it (or insert new data). 因此,仅当您尝试访问数据库中的数据(或插入新数据)时,才会创建数据库。

You have to be carefull when creating a query for to execute.. in particular with spaces and commas. 创建要执行的查询时必须格外小心,尤其是空格和逗号。

change this line 改变这条线

String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);

whit: 丝毫:

String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + " (" + KEY_ID + " INTEGER PRIMARY KEY, " + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CONTACTS_TABLE);

You really didn't created database, you only create instance of your SQLiteOpenHelper but for create or open database you have to use getWritableDatabase() or getReadableDatabase() method. 您实际上并没有创建数据库,仅创建SQLiteOpenHelper的实例,但是要创建或打开数据库,则必须使用getWritableDatabase()或getReadableDatabase()方法。

SQLiteDatabase db = new DataBaseHandler(this).getWritableDatabase(); SQLiteDatabase db =新的DataBaseHandler(this).getWritableDatabase();

in your main activity 在你的主要活动中

SQLiteDatabase sql;
sql=db.getWritableDatabase(); (where db is DB Handler)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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