2011-02-26 67 views
0

我正在關注Android的SQLiteDatabase教程,並且在這裏按下按鈕時它可以正常工作,但對於我來說它不適用。我添加了一些嘗試方法,看看發生了什麼,但它仍然無法正常工作。在這裏我的代碼:我的代碼在訪問SQLite數據庫時出了什麼問題?

public class MyDatabasaDemo extends Activity { 
    private static final String DATABASE_NAME = "JADB.db"; 
    private static final String DATABASE_TABLE = "myTable"; 
    private static final String DATABASE_CREATE = "create table"+ DATABASE_TABLE; 


    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Button butCreate = (Button) findViewById(R.id.myButCreate); 
     Button butAdd = (Button) findViewById(R.id.myButAdd); 
     Button butCount = (Button) findViewById(R.id.myButCount); 
     Button butShow = (Button) findViewById(R.id.myButShow); 

     butCreate.setOnClickListener(new OnClickListener(){ 

      public void onClick(View arg0) { 
       SQLiteDatabase myDB; 
       try{ 
       myDB = openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null); 
       myDB.execSQL(DATABASE_CREATE); 
       myDB.close(); 

       Toast.makeText(getApplicationContext(), "Table Creat", Toast.LENGTH_SHORT).show(); 

       }catch(SQLException e){ 
        Toast.makeText(getApplicationContext(), "SQLException", Toast.LENGTH_SHORT); 

       } 
      } 

     }); 

     butAdd.setOnClickListener(new OnClickListener(){ 

      public void onClick(View arg0) { 
       SQLiteDatabase myDB; 

       myDB = openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null); 

       ContentValues newRow = new ContentValues(); 
       newRow.put("col1", "ok"); 
       myDB.insert(DATABASE_TABLE, null, newRow); 

       myDB.close(); 


       Toast.makeText(getApplicationContext(), "row added", Toast.LENGTH_SHORT).show(); 

      } 

     }); 


     butCount.setOnClickListener(new OnClickListener(){ 

      public void onClick(View arg0) { 
       SQLiteDatabase myDB; 

       myDB = openOrCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null); 

       String[] resultColumns = new String[]{"_id","col1"}; 

     Cursor allRows = myDB.query(DATABASE_TABLE, resultColumns, null, null, null, null, null, null); 

       myDB.close(); 

       Integer c = allRows.getCount(); 

       Toast.makeText(getApplicationContext(), "count: "+c.toString(), Toast.LENGTH_SHORT).show(); 

      } 

     }); 
    } 

數據庫創建,但弗里斯特按鈕這麼想的工作裏面的烤麪包的消息,所以我想,如果它不是關閉。

thankyou

+0

@ user583713 - 您可以刪除不初步認識的代碼 - 我不知道哪一個按鈕點擊收聽你所談論的。 – tpow 2011-02-26 22:14:29

+0

create table語句看起來不正確,它會丟失表關鍵字和表名之間的空格。 – david 2011-02-26 22:22:32

+0

您應該記錄異常消息以獲取有關該問題的更多信息。 – david 2011-02-26 22:23:30

回答

1

您試圖創建一個沒有列的表,然後插入一條記錄。你應該改變你的數據庫創建SQL:

private static final String COLUMN_ID = "_id"; 
private static final String COLUMN_NAME = "col1"; 
private static final String DATABASE_CREATE = "create table "+ DATABASE_TABLE +" ("+ 
    COLUMN_ID + " integer primary key autoincrement, " + 
    COLUMN_NAME +" text not null" 
    +");"; 
相關問題