在SQLite中创建表?

时间:2017-12-09 19:34:01

标签: android sqlite android-sqlite

我想创建SQLite数据库和table.this是我的代码请告诉我这段代码中的错误在哪里

/**
 * Created by Parsian computer on 12/9/2017.
 */

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final Integer COL_ID = 0;
    public static final String COL_FirstName = "FirstName";
    public static final String COL_LastName = "LastName";
    public static final String COL_AccountName = "AccountName";
    public static final String COL_Password = "Password";
    public static final String COL_RePassword = "RePassword";
    public static final String Table_Name = "BaharTables";
    private static final String DatabaseName = "BaharDatabase.db";
    public static final String COL_ProductName = "ProductName";
    public static final String COL_ProductPrice = "ProductPrice";
    public static final String COL_IMAGE = "Images";

    public DatabaseHelper(Context context) {
        super(context, DatabaseName, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        String Table_Create="CREATE TABLE "+Table_Name+
                " ("+COL_ID+" integer primary key autoincrement,"+
                COL_FirstName+" Text,"+
                COL_LastName+" Text,"+
                COL_AccountName+" Text,"+
                COL_Password+" Text,"+
                COL_RePassword+" Text,"+
                COL_ProductName+" Text,"+
                COL_ProductPrice+" Text,"+
                COL_IMAGE+" Blob )";
        db.execSQL(Table_Create);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("Drop Table if exists "+Table_Name);
onCreate(db);
    }

在android-studio中没有显示任何错误,但表格没有创建

2 个答案:

答案 0 :(得分:0)

只有在尝试从应用程序的任何其他部分访问数据库时,才会调用onCreate方法。只需调用getReadableDatabase(),就可以创建数据库。

答案 1 :(得分:0)

您不能让列名以数字开头(除非引用,例如'0',“0”,[0]或`0` )。

你有: -

..... ("+COL_ID+" integer primary key autoincrement,"+ .....

COL_ID定义为0(即private static final Integer COL_ID = 0;

所以上面相当于....(0 integer primary key autoincrement, ......

您可以尝试更改: -

    private static final Integer COL_ID = 0;

来: -

    public static final String COL_ID = "_id";

完成上述更改后,您应该在重新运行应用程序之前执行以下操作之一: -

  • 删除应用程序的数据。
  • 卸载应用程序。
  • super(context, DatabaseName, null, 1)更改为super(context, DatabaseName, null, 2)

需要执行上述操作之一是因为onCreate方法仅在创建数据库时自动运行一次。前两个选项将删除数据库。第三个选项将导致onUpgrade方法运行,然后调用onCreate方法。