Sqlite语法错误

时间:2015-02-12 19:15:42

标签: sqlite android-sqlite

运行代码时遇到一个问题。我有一个SQlite数据库,有些列,一个是这个列(列CHECK的值为0或1)。我检查此列以确定要在一个活动中显示的行。值1表示Class Hate,值0表示Class Love。在这个类中,我在读取数据库的方法中传递了这个值,以便在这个方法中说我要放入活动的行,但是它没有工作

我收到此错误:

02-12 13:57:18.782 866-866 / com.example.lovehate.loveandhate E / SQLiteLog:(1)near" CHECK":语法错误 02-12 13:57:18.792 866-866 / com.example.lovehate.loveandhate D / AndroidRuntime:关闭VM 02-12 13:57:18.792 866-866 / com.example.lovehate.loveandhate W / dalvikvm:threadid = 1:线程退出,未捕获异常(组= 0x41465700) 02-12 13:57:18.842 866-866 / com.example.lovehate.loveandhate E / AndroidRuntime:FATAL EXCEPTION:main     java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.lovehate.loveandhate / com.example.lovehate.loveandhate.Love}:android.database.sqlite.SQLiteException:near" CHECK":syntax错误(代码1):,编译时:SELECT _id,nombre,imagen,checki FROM lovehateTable WHERE CHECK = 0             在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)             在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)             在android.app.ActivityThread.access $ 600(ActivityThread.java:141)             在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1256)             在android.os.Handler.dispatchMessage(Handler.java:99)             在android.os.Looper.loop(Looper.java:137)             在android.app.ActivityThread.main(ActivityThread.java:5103)             at java.lang.reflect.Method.invokeNative(Native Method)             在java.lang.reflect.Method.invoke(Method.java:525)             在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)             在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)             at dalvik.system.NativeStart.main(Native Method)      引起:android.database.sqlite.SQLiteException:near" CHECK&#34 ;:语法错误(代码1):,同时编译:SELECT _id,nombre,imagen,checki FROM lovehateTable WHERE CHECK = 0             在android.database.sqlite.SQLiteConnection.nativePrepareStatement(原生方法)

数据库类

公共类DataBaseHelper扩展了SQLiteOpenHelper {

//Datos de la tabla
final private static String NAME = "lHate03_db"; //nombre DDBB
final static String TABLE_LOVEHATE = "lovehateTable"; //Nombre de la tabla
//Columnas
final static String ID = "_id";
final static String ITEM = "nombre";
final static String CHECK = "checki";
final static String IMG = "imagen";


//comandos
final static String[] columns = {ID, ITEM, IMG, CHECK};
final private static String CREATE_CMD =

        "CREATE TABLE " + TABLE_LOVEHATE + " ("
                + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + ITEM + " TEXT NOT NULL, "
                + IMG + " STRING, "
                + CHECK + " INTEGER DEFAULT 1) ";


final private static Integer VERSION = 1;
final private Context mContext;


//Modos edicion
public static final String C_MODO  = "modo" ;
public static final int C_VISUALIZAR = 551 ;
public static final int C_CREAR = 552 ;
public static final int C_EDITAR = 553 ;


//Constructor
public DataBaseHelper(Context context) {
    super(context, NAME, null, VERSION);
    this.mContext = context;
}

//Creación de la base de datos
@Override
public void onCreate(SQLiteDatabase db) {
    //Creamos la base de datos
    Log.i(this.getClass().toString(), "Tabla AMORODIO creada");
    db.execSQL(CREATE_CMD);
    //La rellenamos
    ContentValues values = new ContentValues();


    values.put(DataBaseHelper.ITEM, "Vetusta Morla");
    values.put(DataBaseHelper.CHECK, 0);
    values.put(DataBaseHelper.IMG, "");
    db.insert(DataBaseHelper.TABLE_LOVEHATE, null, values);
    values.clear();

    values.put(DataBaseHelper.ITEM, "ColdPlay");
    values.put(DataBaseHelper.CHECK, 0);
    values.put(DataBaseHelper.IMG, "");
    db.insert(DataBaseHelper.TABLE_LOVEHATE, null, values);
    values.clear();

    values.put(DataBaseHelper.ITEM, "All India Radio");
    values.put(DataBaseHelper.CHECK, 1);
    values.put(DataBaseHelper.IMG, "");
    db.insert(DataBaseHelper.TABLE_LOVEHATE, null, values);
    Log.i(this.getClass().toString(), "Datos insertados");
}

//Actualización de la base de datos
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // N/A
}

@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // N/A
}

//Borrando de la base de datos
void deleteDatabase() {
    mContext.deleteDatabase(NAME);
}

//Lectura de la base de datos
public Cursor readArtistas(SQLiteDatabase db, int love) {
    String consulta = "";
    if (love == 1)
    {
        consulta = " CHECK=1 ";
    }
    if (love == 0)
    {
        consulta = " CHECK=0 ";
    }
    return db.query(TABLE_LOVEHATE, columns, consulta, new String[] {}, null, null, null);
}


/**
 * Devuelve cursor con todos las columnas del registro
 */
public Cursor getRegistro(long id) throws SQLException
{
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor c = db.query( true, TABLE_LOVEHATE, columns, ID + "=" + id, null, null, null, null, null);

    //Nos movemos al primer registro de la consulta
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

/**
 * Inserta los valores en un registro de la tabla
 */
public long insert(ContentValues reg)
{
    SQLiteDatabase db=this.getWritableDatabase();
    return db.insert(TABLE_LOVEHATE, null, reg);
}

/**
 * Inserta los valores en un registro de la tabla
 */
public long update(ContentValues reg)
{
    SQLiteDatabase db=this.getWritableDatabase();
    if (reg.containsKey(ID))
    {
        //
        // Obtenemos el id y lo borramos de los valores
        //
        long id = reg.getAsLong(ID);

        reg.remove(ID);

        //
        // Actualizamos el registro con el identificador que hemos extraido
        //
        return db.update(TABLE_LOVEHATE, reg, "_id=" + id, null);
    }
    return db.insert(TABLE_LOVEHATE, null, reg);
}

}

LoveClass

公共类Love扩展ListActivity {

private DataBaseHelper mDbHelper;
private SQLiteDatabase db;
private SimpleCursorAdapter mAdapter;
private Cursor c;

private static final String TAG = "Datos";

public static final String C_MODO  = "modo" ;
public static final int C_VISUALIZAR = 551 ;
public static final int C_CREAR = 552 ;
public static final int C_EDITAR = 553 ;
public static final String C_TIPO = "tipo";
public static final int IS_LOVE = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_love);

    // Creamos una nueva DataBase
    mDbHelper = new DataBaseHelper(this);
    db = mDbHelper.getWritableDatabase();

    //Leemos la BBDD y mostramos la info
    Cursor c = mDbHelper.readArtistas(db, 0);
    mAdapter = new SimpleCursorAdapter(this, R.layout.list_layout, c, DataBaseHelper.columns,
            new int[] {R.id._id, R.id.nombre}, 0);

    setListAdapter(mAdapter);


    //Añadimos el listener del boton
    final Button boton=(Button) findViewById(R.id.addBtn);
    boton.setOnClickListener(new Button.OnClickListener(){
          @Override
          public void onClick(View v) {

          Intent i = new Intent(Love.this, Formulario.class);
            i.putExtra(C_MODO, C_CREAR);
            i.putExtra(C_TIPO, IS_LOVE);
          startActivityForResult(i, C_CREAR);
          }
    }
    );
}

public void editHandler(View v) {
    //get the row the clicked button is in
    LinearLayout vwParentRow = (LinearLayout)v.getParent();
    TextView id =(TextView) vwParentRow.findViewById(R.id._id);
    Intent i = new Intent(Love.this, Formulario.class);

    i.putExtra(C_MODO, C_EDITAR);
    i.putExtra(mDbHelper.ID, Long.valueOf((String)id.getText()));


    this.startActivityForResult(i, C_EDITAR);
}

public void viewHandler(View v) {
    //get the row the clicked button is in
    LinearLayout vwParentRow = (LinearLayout)v.getParent();
    TextView id =(TextView) vwParentRow.findViewById(R.id._id);
    Intent i = new Intent(Love.this, Formulario.class);

    i.putExtra(C_MODO, C_VISUALIZAR);
    i.putExtra(mDbHelper.ID, Long.valueOf((String)id.getText()));


    this.startActivityForResult(i, C_VISUALIZAR);
}


//Visualizar un dato en Formulario
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
    super.onListItemClick(l, v, position, id);
    // Llamamos a la Actividad Formulario indicando el modo visualización y el identificador del registro
    Intent i = new Intent(Love.this, Formulario.class);
    i.putExtra(C_MODO, C_VISUALIZAR);
    i.putExtra(mDbHelper.ID, id);

    startActivityForResult(i, C_VISUALIZAR);
}

//CApturamos la respuesta a la creación de registro
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    //
    // Nos aseguramos que es la petición que hemos realizado
    //
    switch(requestCode)
    {
        case C_CREAR:
            if (resultCode == RESULT_OK)
            //Leemos la base de datos y mostramos la informacion
            c=mAdapter.getCursor();
            c=mDbHelper.readArtistas(db, 0);
            mAdapter.changeCursor(c);
            mAdapter.notifyDataSetChanged();
        case C_EDITAR:
            if (resultCode == RESULT_OK)
            //Leemos la base de datos y mostramos la informacion
            c=mAdapter.getCursor();
            c=mDbHelper.readArtistas(db, 0);
            mAdapter.changeCursor(c);
            mAdapter.notifyDataSetChanged();
        default:
            super.onActivityResult(requestCode, resultCode, data);
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_love, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

HateClass

public class Hate扩展了ListActivity {

private DataBaseHelper mDbHelper;
private SQLiteDatabase db;
private SimpleCursorAdapter mAdapter;
private Cursor c;

private static final String TAG = "Datos";

public static final String C_MODO  = "modo" ;
public static final int C_VISUALIZAR = 551 ;
public static final int C_CREAR = 552 ;
public static final int C_EDITAR = 553 ;
public static final String C_TIPO = "tipo";
public static final int IS_LOVE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hate);
    // Creamos una nueva DataBase
    mDbHelper = new DataBaseHelper(this);
    db = mDbHelper.getWritableDatabase();

    //Leemos la BBDD y mostramos la info
    Cursor c = mDbHelper.readArtistas(db, 1);
    mAdapter = new SimpleCursorAdapter(this, R.layout.list_layout, c, DataBaseHelper.columns,
            new int[] {R.id._id, R.id.nombre}, 0);

    setListAdapter(mAdapter);


    //Añadimos el listener del boton
    final Button boton=(Button) findViewById(R.id.addBtn);
    boton.setOnClickListener(new Button.OnClickListener(){
    @Override
    public void onClick(View v) {
        Intent i = new Intent(Hate.this, Formulario.class);
            i.putExtra(C_MODO, C_CREAR);
            i.putExtra(C_TIPO, IS_LOVE);
            startActivityForResult(i, C_CREAR);
            }
        }
    );
}

public void editHandler(View v) {
    //get the row the clicked button is in
    LinearLayout vwParentRow = (LinearLayout)v.getParent();
    TextView id =(TextView) vwParentRow.findViewById(R.id._id);
    Intent i = new Intent(Hate.this, Formulario.class);

    i.putExtra(C_MODO, C_EDITAR);
    i.putExtra(mDbHelper.ID, Long.valueOf((String)id.getText()));


    this.startActivityForResult(i, C_EDITAR);
}

public void viewHandler(View v) {
    //get the row the clicked button is in
    LinearLayout vwParentRow = (LinearLayout)v.getParent();
    TextView id =(TextView) vwParentRow.findViewById(R.id._id);
    Intent i = new Intent(Hate.this, Formulario.class);

    i.putExtra(C_MODO, C_VISUALIZAR);
    i.putExtra(mDbHelper.ID, Long.valueOf((String)id.getText()));


    this.startActivityForResult(i, C_VISUALIZAR);
}

// Close database
@Override
protected void onDestroy() {
    mDbHelper.deleteDatabase();
    super.onDestroy();
}

//Visualizar un dato en Formulario
@Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
    super.onListItemClick(l, v, position, id);
    // Llamamos a la Actividad Formulario indicando el modo visualización y el identificador del registro
    Intent i = new Intent(Hate.this, Formulario.class);
    i.putExtra(C_MODO, C_VISUALIZAR);
    i.putExtra(mDbHelper.ID, id);

    startActivityForResult(i, C_VISUALIZAR);
}

//CApturamos la respuesta a la creación de registro
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    //
    // Nos aseguramos que es la petición que hemos realizado
    //
    switch(requestCode)
    {
        case C_CREAR:
            if (resultCode == RESULT_OK)
                //Leemos la base de datos y mostramos la informacion
            c=mAdapter.getCursor();
            c=mDbHelper.readArtistas(db, 1);
            mAdapter.changeCursor(c);
            mAdapter.notifyDataSetChanged();
        case C_EDITAR:
            if (resultCode == RESULT_OK)
                //Leemos la base de datos y mostramos la informacion
            c=mAdapter.getCursor();
            c=mDbHelper.readArtistas(db, 1);
            mAdapter.changeCursor(c);
            mAdapter.notifyDataSetChanged();
        default:
            super.onActivityResult(requestCode, resultCode, data);
    }
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_hate, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

1 个答案:

答案 0 :(得分:1)

您将列命名为“checki”:

final static String CHECK = "checki";

 // ...

    "CREATE TABLE " + TABLE_LOVEHATE + " ("
            + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + ITEM + " TEXT NOT NULL, "
            + IMG + " STRING, "
            + CHECK + " INTEGER DEFAULT 1) ";

但是你把它称为CHECK:

//Lectura de la base de datos

public Cursor readArtistas(SQLiteDatabase db, int love) {
    String consulta = "";
    if (love == 1)
    {
        consulta = " CHECK=1 ";
    }
    if (love == 0)
    {
        consulta = " CHECK=0 ";
    }
    return db.query(TABLE_LOVEHATE, columns, consulta, new String[] {}, null, null, null);
}

您需要:

1 重命名列CHECK(注意括号)

final static String CHECK = "[CHECK]";

或(更好)

2 用它的正确名称引用它:

//Lectura de la base de datos

public Cursor readArtistas(SQLiteDatabase db, int love) {
    String consulta = "";
    if (love == 1)
    {
        consulta = " checki=1 ";
    }
    if (love == 0)
    {
        consulta = " checki=0 ";
    }
    return db.query(TABLE_LOVEHATE, columns, consulta, new String[] {}, null, null, null);