gpt4 book ai didi

android - 未创建 SQLite 数据库

转载 作者:行者123 更新时间:2023-11-29 16:08:29 26 4
gpt4 key购买 nike

这段代码没有创建我的数据库。我想在创建表时创建一个带有一些默认值的预填充表。虽然执行时没有错误。有帮助吗?

数据库助手代码:

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");

}


}

主要 Activity 代码:

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;
}

}

最佳答案

试试这段代码

在你的 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");

}

在您的 Activity 中:

    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();
}

然后在你的 Activity 中编码:

            DatabaseHelper helper = new DatabaseHelper(MainActivity.this);
helper.save(12, "Clear");

希望对你有所帮助。

关于android - 未创建 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15768513/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com