此代码未创建我的数据库。我想在创建表时创建一个预先填充的表,其中包含一些默认值。虽然执行时没有错误。有什么帮助吗?
DatabaseHelper代码:
public class DatabaseHelper extends SQLiteOpenHelper {
public static String dbName = "whatever.db";
public static int dbVersion = 2;
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String createTable = "CREATE TABLE smart (UID INTEGER PRIMARY KEY, NAME TEXT);";
db.execSQL(createTable);
ContentValues cv = new ContentValues();
cv.put("UID", 9);
cv.put("NAME", "clear");
db.insert("smart", null, cv);
db.close();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS smart");
}
}
MainActivity代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseHelper dbHelper = new DatabaseHelper(this);
dbHelper.close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
答案 0 :(得分:3)
试试这段代码
在您的DatabaseHelper中:
public static String dbName = "whatever.db";
public static int dbVersion = 2;
public DatabaseHelper(Context context) {
super(context, dbName, null, dbVersion);
}
@Override
public void onCreate(SQLiteDatabase db)
{
String createTable = "CREATE TABLE smart (UID INTEGER PRIMARY KEY, NAME TEXT);";
db.execSQL(createTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS smart");
}
并在您的活动中:
DatabaseHelper helper = new DatabaseHelper(MainActivity.this);
SQLiteDatabase myDB = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("UID", 9);
cv.put("NAME", "clear");
myDB.insert("smart", null, cv);
myDB.close();
或在数据库助手中添加此方法:
public void save(int yourUID, String yourText)
{
SQLiteDatabase myDB = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("UID", yourUID);
cv.put("NAME", yourText);
myDB.insert("smart", null, cv);
myDB.close();
}
然后在您的活动中编码:
DatabaseHelper helper = new DatabaseHelper(MainActivity.this);
helper.save(12, "Clear");
我希望,我帮助过你。
答案 1 :(得分:1)
不使用sqliteopenhelper
尝试此操作在您的活动类
中private SqliteDatabase Dbname;
Dbname = this.openOrCreateDatabase(YourDbname, MODE_PRIVATE, null);//inside oncreate()
String createTable = "CREATE TABLE smart (UID INTEGER PRIMARY KEY, NAME TEXT);";
db.execSQL(createTable);
ContentValues cv = new ContentValues();
cv.put("UID", 9);
cv.put("NAME", "clear");
db.insert("smart", null, cv);
db.close();