简体   繁体   中英

SQLiteException: near “” syntax error

My SQLiteOpenHelper class:

public class MyUsersDatabaseAdapter
{
    MyUsersDatabase myUsersDatabase;
    SQLiteDatabase sqLiteDatabase;

public MyUsersDatabaseAdapter(Context context, String name, CursorFactory factory,int version)
{
    myUsersDatabase = new MyUsersDatabase(context, name, factory, version);
}

public long inserDataToDatabase(String firstName,String lastName)
{
    sqLiteDatabase = myUsersDatabase.getWritableDatabase(); // sqliteDatabase is a reference to my database

    ContentValues contentValues = new ContentValues();
    contentValues.put(MyUsersDatabase.FIRST_NAME,firstName ); // First parameter(key) is the name of the column
    contentValues.put(MyUsersDatabase.LAST_NAME, lastName);

    long id = sqLiteDatabase.insert(MyUsersDatabase.TABLE_NAME, null, contentValues);
    return id;
}

static class MyUsersDatabase extends SQLiteOpenHelper
{
    private static final int DATABASE_VERSION = 4;
    private static final String DATABASE_NAME = "usersDatabase";
    private static final String TABLE_NAME = "usersTable";
    private static final String UID = "_id"; // User identification number
    private static final String FIRST_NAME = "First Name"; // Column
    private static final String LAST_NAME = "Last Name"; // Column
    private static final String CREATE_TABLE = "CREATE TABLE " + MyUsersDatabase.DATABASE_NAME + "(" 
    + UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
    + FIRST_NAME + " TEXT, " 
    + LAST_NAME + " TEXT);";
    private static final String DROP_TABLE = "DROP TBALE IF EXIST " + TABLE_NAME;

    private Context context;


    public MyUsersDatabase(Context context, String name, CursorFactory factory,int version)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        this.context = context;
        ToastMessage.message(context, "Constructor was called");
    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {
        ToastMessage.message(context, "onCreate() was called");
        try
        {
            db.execSQL(CREATE_TABLE);
        }
        catch (SQLException e)
        {
            ToastMessage.message(context,"" + e);
        }
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        ToastMessage.message(context, "onUpgrade() was called");
        try
        {
            db.execSQL(DROP_TABLE);
            onCreate(db);
        } 
        catch (SQLException e) 
        {
            ToastMessage.message(context,"" + e);
        }
    }
}

LogCat:

09-14 16:50:13.711: E/SQLiteLog(26257): (1) near "Name": syntax error
09-14 16:50:13.713: E/SQLiteDatabase(26257): Error inserting Last Name= First Name=
09-14 16:50:13.713: E/SQLiteDatabase(26257): android.database.sqlite.SQLiteException: near "Name": syntax error (code 1): , while compiling: INSERT INTO usersTable(Last Name,First Name) VALUES (?,?)
09-14 16:50:13.713: E/SQLiteDatabase(26257):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:894)
09-14 16:50:13.713: E/SQLiteDatabase(26257):    at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:505)
09-14 16:50:13.713: E/SQLiteDatabase(26257):    at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
09-14 16:50:13.713: E/SQLiteDatabase(26257):    at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1570)

So i fet this LogCat after clicking a Button .

Main class:

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up);

    viewsInitialization();

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    myUsersDatabase = new MyUsersDatabaseAdapter(SignUpActivity.this,"UsersDatabase" , null, 1);
contentValues = new ContentValues();

    signUpButton.setOnClickListener(new View.OnClickListener()
    {   
        @Override
        public void onClick(View v) 
        {
            userFirstName = firstNameEditText.getText().toString();
            userLastName = lastNameEditText.getText().toString();

            id = myUsersDatabase.inserDataToDatabase(userFirstName, userLastName);
            if (id < 0)
            {
                ToastMessage.message(SignUpActivity.this, "Unsuccessful row insertion");
            }
            else 
            {
                ToastMessage.message(SignUpActivity.this, "Successful row insertion");
            }
        }
    });
}

And also the Toast "Unsuccessful row insertion".

So whats wrong with my code?

EDIT

After removing blanks from column names i get this LogCat:

9-14 17:17:04.049: E/SQLiteLog(32247): (1) table usersTable has no column named LastName
09-14 17:17:04.051: E/SQLiteDatabase(32247): Error inserting LastName=hsh FirstName=hshsh
09-14 17:17:04.051: E/SQLiteDatabase(32247): android.database.sqlite.SQLiteException: table usersTable has no column named LastName (code 1): , while compiling: INSERT INTO usersTable(LastName,FirstName) VALUES (?,?)
09-14 17:17:04.051: E/SQLiteDatabase(32247):    at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
09-14 17:17:04.051: E/SQLiteDatabase(32247):    at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:894)

You should not use blank in tables names. If you what do do so, you have to use backticks around the names. Better solution is to rename the columns without using blanks.

The problem is that your table has columns with spaces in them, and the column names are not wrapped in tick characters (`). You can solve this problem one of two ways:

1st way (Recommended)

Rename your table columns from "First Name" and "Last Name" to "FirstName" and "LastName" (note the removed space). After doing this, you will need to trigger a call to onUpgrade so your upgrade code is ran (in your case, it will drop the old table so the new table can be created). Afterwards, your column names will match, there will be no whitespace characters, and your database should work great.

After making this change, your old database will still be in tact and needs to be updated with the new columns. You can either delete the old column, or use the onUpgrade feature of SQLiteOpenHelper as mentioned in the previous paragraph.

2nd way (not as good) but including for completeness

Add ticks around your code:

private static final String CREATE_TABLE = "CREATE TABLE " + MyUsersDatabase.DATABASE_NAME + "(" 
+ UID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
+ "`" + FIRST_NAME + "` TEXT, " 
+ "`" + LAST_NAME + "` TEXT);";

This works, but including whitespace characters in column names is generally considered to be bad practice.

Final thought

You can add ticks around the column names either way, since the ticks just define that what is wrapped inside is a single object and should be parsed together. Also, column names with spaces in them are bad practice, you should never include spaces in table names (even though it is possible).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM