这是 DatabaseHelper类,没有编写任何编译错误数据库,但是没有创建任何表,因此已写入所有内容,而我在sqlite3命令行中也遇到了麻烦。我不知道为什么未在 android studio 3.5
中创建它import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "Student";
public static final String COL_1 = "ID";
public static final String COL_2 = "Name";
public static final String COL_3 = "Surname";
public static final String COL_4 = "Marks";
//constructor
public DatabaseHelper( Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+TABLE_NAME+" (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS TEXT )" );
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// below method check wheather tha same name database is exist or not
//if exists it will delete and create new database
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
主要方法
public class MainActivity extends AppCompatActivity {
DatabaseHelper mydb;
EditText mName, mSurname, mMarks;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DatabaseHelper(this);
}
}
答案 0 :(得分:0)
好吧,看来您的做法不正确。请参考以下代码,并尝试了解它们之间的区别。
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "Student";
public static final String COL_1 = "ID";
public static final String COL_2 = "Name";
public static final String COL_3 = "Surname";
public static final String COL_4 = "Marks";
//constructor
public DatabaseHelper( Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+TABLE_NAME+" (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, SURNAME TEXT, MARKS TEXT );" );
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// below method check wheather tha same name database is exist or not
//if exists it will delete and create new database
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
}
主要方法
这与您的不同。原因是,即使您在 DatabaseHelper 中定义了 SQLiteDatabase ,也不会将其称为main方法。因此,您必须在main方法本身中定义它。
public class MainActivity extends AppCompatActivity {
DatabaseHelper dbHelper;
SQLiteDatabase database;
EditText mName, mSurname, mMarks;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DatabaseHelper(this);
database = dbHelper.getWritableDatabase();
}
}