问题描述
我自己写了一个ContentProvider,在执行向SQLiteDatabase数据库中插入一条记录时不成功,打出的log如下:11-27 02:00:11.696: ERROR/Database(997): android.database.sqlite.SQLiteException: table employee has no column named name: , while compiling: INSERT INTO employee(name) VALUES(?); 我的SQLiteOpenHelper类的派生类如下:package com.hgl.test;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;import com.hgl.test.Employees.Employee;public class DBHelper extends SQLiteOpenHelper {private static final String DATABASE_NAME = "Employees.db";private static final int DATABASE_VERSION = 1;public static final String EMPLOYEES_TABLE_NAME = "employee";// 创建数据库public DBHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);Log.i("DBHelper Info===================>>>>>>>","this is DBHelper constructer function");}// 创建时调用,创建一个表@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stubLog.i("DBHelper Info===================>>>>>>>","this is onCreate function");String createTableSQL = "CREATE TABLE " + EMPLOYEES_TABLE_NAME + "("+ Employee._ID + " INTEGER PRIMARY KEY," + Employee.NAME+ " TEXT," + Employee.GENDER + " TEXT," + Employee.AGE+ " INTEGER)";db.execSQL(createTableSQL);Log.d("Create Table=====================>>>>>>>>>>>", "create table "+ EMPLOYEES_TABLE_NAME);}// 版本更新时调用@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stubdb.execSQL("DROP TABLE IF EXISTS "+EMPLOYEES_TABLE_NAME);onCreate(db);}} 自己的ContentProvider派生类如下:public class MyContentProvider extends ContentProvider{ //.........其他的省略........@Overridepublic Uri insert(Uri uri, ContentValues values) {Log.i("Employeeprovider Info===================》》》》》","this is insert function");// 获取数据库实例SQLiteDatabase db = dbHelper.getWritableDatabase();//dbHelper.onCreate(db);//创建表// 插入数据,返回行IDLong rowID = db.insert(DBHelper.EMPLOYEES_TABLE_NAME, Employee.NAME, values);// 如果插入成功返回Uriif (rowID > 0) {Uri empUri = ContentUris.withAppendedId(Employee.CONTENT_URI, rowID);getContext().getContentResolver().notifyChange(empUri, null);return empUri;}return null;}}我在MainActivity中调用Insert方法时就报错,MainActivity中的onCreate方法中调用insert方法:public void insert() {//"content://com.hgl.test.employees/employee";Uri uri = Employee.CONTENT_URI;// 实例化ContentValuesContentValues values = new ContentValues();values.put(Employee.NAME, "android");//values.put(Employee.GENDER, "software");//values.put(Employee.AGE, 3);// 获取ContentResolver,并执行插入getContentResolver().insert(uri, values);}请问这是哪里的错误呢?
解决方案
你的Primary key处理出错。 如果你想他为自增的,可以写为: INTEGER PRIMARY KEY AUTOINCREMENT,否则,插入时候自己指定唯一Id.异常的提示也说清楚了。 是插入时缺少列。