2013-10-20 120 views
0

我花了太多時間來解決這個問題。希望你們(或女孩......)能幫助我!SQLiteException:插入數據庫時​​出錯

LogCat說錯誤是'附近「設置」「,但我無法找到問題。

logcat的

10-20 17:21:05.969 2135-2135/com.sahota.breakfit E/SQLiteLog﹕ (1) near "set": syntax error 
10-20 17:21:05.969 2135-2135/com.sahota.breakfit E/SQLiteDatabase﹕ Error inserting set_length=15 break_timer=60 exercise_name=BenchPress set=5 
    android.database.sqlite.SQLiteException: near "set": syntax error (code 1): , while compiling: INSERT INTO db_table(set_length,break_timer,exercise_name,set) VALUES (?,?,?,?) 
      at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) 
      at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:882) 
      at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493) 
      at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) 
      at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58) 
      at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31) 
      at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1467) 
      at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339) 
      at com.sahota.breakfit.DBOpenHelper.insertRecord(DBOpenHelper.java:86) 
      at com.sahota.breakfit.MainActivity.onCreate(MainActivity.java:51) 
      at android.app.Activity.performCreate(Activity.java:5104) 
      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 
      at android.app.ActivityThread.access$600(ActivityThread.java:141) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 
      at android.os.Handler.dispatchMessage(Handler.java:99) 
      at android.os.Looper.loop(Looper.java:137) 
      at android.app.ActivityThread.main(ActivityThread.java:5041) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:511) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 
      at dalvik.system.NativeStart.main(Native Method) 

MainActivity

public class MainActivity extends Activity { 
    DBOpenHelper db = new DBOpenHelper(this); 

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

     try { 
      String destPath = "/data/data/" + getPackageName() + "/databases/DBBreakFit"; 
      File f = new File(destPath); 
      if (!f.exists()) { 
       CopyDB(getBaseContext().getAssets().open("mydb"), 
         new FileOutputStream(destPath)); 
      } 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     // ---add an assignment--- 

     try { 
      db.open(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     long 
       id = db.insertRecord("BenchPress", "60", "5", "15"); 
       id = db.insertRecord("Cablecrunch", "120", "6", "20");   
       id = db.insertRecord("Squat", "30", "2", "120"); 
     db.close(); 

     //---get all Records--- 
     try { 
      db.open(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     Cursor c = db.getAllRecords(); 
     if (c.moveToFirst()) { 
      do { 
       DisplayRecord(c); 
      } while (c.moveToNext()); 
     } 
     db.close(); 

     //---get a Record--- 
     try { 
      db.open(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     Cursor cursor = null; 
     try { 
      cursor = db.getRecord(2); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     if (cursor.moveToFirst()) 
      DisplayRecord(cursor); 
     else 
      Toast.makeText(this, "No Assignments found", Toast.LENGTH_LONG).show(); 
     db.close(); 


     //---update Record--- 
     try { 
      db.open(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     if (db.updateRecord(1, "Hello Android", "2/19/2012", "DPR 224", "First Android Project")) 
      Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show(); 
     else 
      Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show(); 
     db.close(); 

     //---delete a Record--- 
     try { 
      db.open(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     if (db.deleteContact(1)) 
      Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show(); 
     else 
      Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show(); 
     db.close(); 


    } 

    public void TestProfilesMain(View view) { 
     Intent intent = new Intent(this, ProfilesMain.class); 
     startActivity(intent); 

    } 

DBOpenHelper

package com.sahota.breakfit; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteException; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 

import java.sql.SQLException; 

/** 
* Created by Harjit S. Sahota on 14-10-13. 
*/ 
public class DBOpenHelper { 
    public static final String LOG_CAT = "logcat"; 

    public static final String KEY_ROWID = "id"; 
    public static final String EXERCISE_NAME = "exercise_name"; 
    public static final String BREAK_TIMER = "break_timer"; 
    public static final String SET = "set"; 
    public static final String SET_LENGTH = "set_length"; 
    private static final String TAG = "DBOpenHelper"; 

    private static final String DATABASE_NAME = "DBName"; 
    private static final String DATABASE_TABLE = "db_table"; 
    private static final int DATABASE_VERSION = 2; 

    private static String DATABASE_CREATE = "create table if not exists profile(id integer primary key autoincrement, " + 
      "exercise_name VARCHAR not null, break_timer VARCHAR not null, set VARCHAR not null, set_length VARCHAR not null);"; 

    private final Context context; 

    private DatabaseHelper DBHelper; 
    private SQLiteDatabase db; 


    public DBOpenHelper(Context ctx) { 
     this.context = ctx; 
     DBHelper = new DatabaseHelper(context); 
    } 

    private static class DatabaseHelper extends SQLiteOpenHelper { 

     DatabaseHelper(Context context) { 
      super(context, DATABASE_NAME, null, DATABASE_VERSION); 
     } 

     @Override 
     public void onCreate(SQLiteDatabase db) { 

      try { 
       db.execSQL(DATABASE_CREATE); 
      } catch (SQLiteException e) { 
       e.printStackTrace(); 
      } 

     } 

     @Override 
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
      Log.w(TAG, "Upgrading database from version" + oldVersion + " to " + newVersion + " which will destroy all old data!"); 
      db.execSQL("DROP TABLE IF EXISTS profile"); 
      onCreate(db); 

     } 
    } 

    public DBOpenHelper open() throws SQLException { 
     db = DBHelper.getWritableDatabase(); 
     return this; 
    } 

    public void close() { 
     DBHelper.close(); 
    } 

    public long insertRecord(String exerciseName, String breakTimer, String set, String setLength) { 
     ContentValues initialValues = new ContentValues(); 
     initialValues.put(EXERCISE_NAME, exerciseName); 
     initialValues.put(BREAK_TIMER, breakTimer); 
     initialValues.put(SET, set); 
     initialValues.put(SET_LENGTH, setLength); 

     return db.insert(DATABASE_TABLE, null, initialValues); 
    } 

    public boolean deleteContact(long rowID) { 
     return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowID, null) > 0; 
    } 

    public Cursor getAllRecords() { 
     return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, EXERCISE_NAME, BREAK_TIMER, SET, SET_LENGTH}, null, null, null, null, null); 
    } 

    public Cursor getRecord(long rowId) throws SQLException { 
     Cursor mCursor = 
       db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, 
         EXERCISE_NAME, BREAK_TIMER, SET, SET_LENGTH}, 
         KEY_ROWID + "=" + rowId, null, null, null, null, null); 
     if (mCursor != null) { 
      mCursor.moveToFirst(); 
     } 
     return mCursor; 
    } 

    public boolean updateRecord(long rowId, String exerciseName, String breakTimer, String set, String setLength) { 
     ContentValues args = new ContentValues(); 
     args.put(EXERCISE_NAME, exerciseName); 
     args.put(BREAK_TIMER, breakTimer); 
     args.put(SET, set); 
     args.put(SET_LENGTH, setLength); 

     return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) >0; 
    } 
} 

ProfilesCreate

public class ProfilesCreate extends Activity { 
    DBOpenHelper db = new DBOpenHelper(this); 

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

    } 

    public void addExercise(View view) { 
     //Getting data from Profiles create-form 
     EditText exerciseName = (EditText) findViewById(R.id.exercisename_edittext); 
     EditText breakTimer = (EditText) findViewById(R.id.breaktimer_edittext); 
     EditText set = (EditText) findViewById(R.id.set_edittext); 
     EditText setLength = (EditText) findViewById(R.id.set_edittext); 

     try { 
      db.open(); 
     } catch (SQLException e) { 
      e.printStackTrace(); 
     } 
     long id = db.insertRecord(exerciseName.getText().toString(), 
       breakTimer.getText().toString(), 
       set.getText().toString(), 
       setLength.getText().toString()); 
     db.close(); 

     //After submitting, replace the text with an empty character. 
     exerciseName.setText(""); 
     breakTimer.setText(""); 
     set.setText(""); 
     setLength.setText(""); 

     Toast.makeText(ProfilesCreate.this, "Exercise Added!", Toast.LENGTH_LONG).show(); 
    } 

    public void addExerciseButton(View view) { 
     Intent intent = new Intent(this, ProfilesShow.class); 
     startActivity(intent); 
    } 
} 

回答

1

set是SQL保留關鍵字,但你要使用它作爲一個表字段的名稱。

+0

**謝謝安迪!這解決了這個問題。然而,一個新的出現。 LogCat說:** E/SQLiteLog:(1)沒有這樣的表:db_table E/SQLiteDatabase:錯誤插入set_length = 15 sets = 5 break_timer = 60 exercise_name = BenchPress android.database.sqlite.SQLiteException:沒有這樣的表:db_table(code 1):,while compiling:INSERT INTO db_table(set_length,sets,break_timer,exercise_name)VALUES(?,?,?,?) – ymerdrengene

+0

它說沒有這樣的表「db_table」,這應該是足夠的給你一個暗示爲什麼它崩潰。事實上,如果仔細查看'DBOpenHelper'類,您可能會注意到'DATABASE_TABLE'字段已聲明,但在創建表時未使用。相反,你創建'profile'表:'創建表如果不存在profile(...' –

1

set是一個保留的SQL關鍵字,如果你喜歡,你作爲一個列名,然後將其括在重音符 像

`set` 

希望這有助於

1

表名DATABASE_CREATE字符串profile 。但是你已經聲明DATABASE_TABLE = "db_table"並在插入函數中使用它。所以正確聲明爲DATABASE_TABLE = "profile"

+0

**謝謝Abhishek!這個幫助解決了一些問題,但是出現了一個新的錯誤:** 1507-1507 /com.sahota.breakfit E/AndroidRuntime:致命例外:main java.lang.RuntimeException:無法啓動活動ComponentInfo {com.sahota.breakfit/com.sahota.breakfit.MainActivity}:android.database.sqlite.SQLiteException:沒有這樣的表:配置文件(代碼1):,而編譯時:SELECT ID,exercise_name,break_timer,sets,set_length從配置文件 – ymerdrengene

+0

將您的'DATABASE_VERSION'更改爲3並再次運行它! –

+0

不合用它沒有工作Abhishek – ymerdrengene

0

我已決定「殺死」該項目,並使用了一種完全不同的方法,因爲我無法解決問題。感謝那些評論並試圖幫助的人:)

和平