我已经编写了下面的代码,用于在数据库中插入一组信息,但遗憾的是它已经关闭了,我不知道为什么。
我查看了logcat,并了解问题在于这个lin db = dbHelper.getWritableDatabase();
任何人都可以帮助我理解原因并解决这个问题吗?
提前致谢
mainActivity:
public class MainActivity extends Activity {
DBHelper dbHelper = null;
SQLiteDatabase db = null;
ContentValues values = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new DBHelper(this, "simple_db", null, 1);
db = dbHelper.getWritableDatabase();
values = new ContentValues();
values.put("name", "Barry");
values.put("amount", "100");
db.insert("simpletable", "", values);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
DBHelper:
public class DBHelper extends SQLiteOpenHelper{
Context c;
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String creatString = "CREATE TABLE IF NOT EXISTS simpletable" +
"(_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name TEXT NOT NULL"
+ "amount INTEGER NOT NULL);";
db.execSQL(creatString);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
String dropString =
"DROP TABLE IF EXISTS simpletable;";
db.execSQL(dropString);
onCreate(db);
}
}
答案 0 :(得分:0)
将onCreate()方法更改为:
@Override
public void onCreate(SQLiteDatabase db) {
String creatString = "CREATE TABLE IF NOT EXISTS simpletable" +
"(_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name TEXT NOT NULL,"
+ "amount INTEGER NOT NULL);";
db.execSQL(creatString);
}
所有你都没事。
您的CREATE TABLE语句构造错误,第二行和第三行之间缺少逗号。