SQLite插入数据返回-1,报near 'occured'语法错误求助
Hey there! Let's break down why your insert is failing with a -1 return value and that pesky syntax error in Logcat.
The Root Cause
Looking at your error log:
05-06 20:58:45.446 13631-13631/com.example.android.disasterreporter E/SQLiteLog: (1) near "occured": syntax error
The problem boils down to column names with spaces like last occured and votes for past. SQLite doesn't natively recognize identifiers (like column names) with spaces—when it hits the space in last occured, it interprets "occured" as a new SQL keyword instead of part of the column name, triggering the syntax error.
How to Fix It
You’ve got two reliable options to resolve this:
Option 1: Wrap Space-Containing Column Names (Quick Fix)
If you want to keep your current column names, you need to wrap them in **backticks ()** every time you reference them in SQL (including when building your ContentValues` for inserts).
For example, when creating your table:
CREATE TABLE your_table_name ( _id INTEGER PRIMARY KEY, disaster INTEGER, `last occured` INTEGER, `location` TEXT, `votes for past` INTEGER, -- Wrap any other space-containing columns here );
And when inserting via Android's ContentValues:
ContentValues values = new ContentValues(); values.put("_id", 2); values.put("disaster", 3); // Wrap space-containing column keys in backticks values.put("`last occured`", 5); values.put("location", "loc"); values.put("`votes for past`", 7); // Add remaining values here long result = db.insert("your_table_name", null, values);
Option 2: Rename Columns to Use Underscores (Best Practice)
A cleaner, more maintainable fix is to replace spaces in column names with underscores—this follows standard database naming conventions and eliminates syntax headaches entirely.
Rename columns like:
last occured→last_occuredvotes for past→votes_for_past
Your insert code then becomes simple and error-proof, no wrapping needed:
ContentValues values = new ContentValues(); values.put("_id", 2); values.put("disaster", 3); values.put("last_occured", 5); values.put("location", "loc"); values.put("votes_for_past", 7); // Add remaining values here long result = db.insert("your_table_name", null, values);
Quick Final Check
Double-check that your ContentValues keys match your column names exactly—even a tiny typo (like missing a backtick or misspelling "occurred") can bring back this error.
内容的提问来源于stack exchange,提问作者Eric Garcia

