尝试在SQLite数据库中保存数据时出错。我的应用程序有两个EditText字段,当用户点击“保存”时,输入的数据必须保存在数据库中。
我正在使用android studio 3.0.1。贝娄是我得到的错误:
16:13:01.270 12710-12710/com.vysh.gridlayoutmanagerrecyclerview
E/SQLiteLog: (1) no such table: myTable
02-03 16:13:01.277 12710-12710/com.vysh.gridlayoutmanagerrecyclerview
E/SQLiteDatabase: Error inserting Password=123 Name=luane
android.database.sqlite.SQLiteException: no such table: myTable (code
1): , while compiling: INSERT INTO myTable(Password,Name) VALUES (?,?)
at
android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
Method)
当用户点击“保存”按钮时,将调用方法insertData()。贝娄是包含这种方法的类:
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
class MyDbAdapter {
MyDbHelper helper;
public MyDbAdapter(Context context)
{
helper = new MyDbHelper(context);
}
public long insertData(String name, String password)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(MyDbHelper.NAME, name);
contentValues.put(MyDbHelper.PASSWORD, password);
long id = db.insert(MyDbHelper.TABLE_NAME, null , contentValues);
//Toast.makeText(context, message, Toast.LENGTH_LONG).show();
return id;
}
static class MyDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDatabase";
private static final String TABLE_NAME = "myTable";
private static final int DATABASE_Version = 1;
private static final String UID="_id";
private static final String NAME = "Name";
private static final String PASSWORD= "Password";
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME +
"( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ "VARCHAR(225)" + PASSWORD+"VARCHAR(225));";
// private static final String DROP_TABLE ="DROP TABLE IF EXISTS "+TABLE_NAME;
private Context context;
public MyDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_Version);
this.context=context;
Message.message(context,"Started...");
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
Message.message(context,"TABLE CREATED");
} catch (Exception e) {
Message.message(context,""+e);
}
}
}// end of MyDbHelper
}
欢迎任何帮助
答案 0 :(得分:0)
您在列名和列类型之间省略了空格。这将导致由于语法错误(列名不能包含 (
)而未创建表。)
在您单击“保存”按钮之前未检测到此原因的原因是,在调用getReabableDatabase
或getWriteableDatabase
之前,不会创建/打开数据库。
你应该改变: -
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME +
"( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ "VARCHAR(225)" + PASSWORD+"VARCHAR(225));";
类似于: -
private static final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME +
"( "+UID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +NAME+ " VARCHAR(225)" + PASSWORD+" VARCHAR(225));";
请注意,您需要在进行更改后删除应用程序的数据或卸载应用程序,以便删除数据库,从而允许运行onCreate
方法。