2013-08-26 28 views
0

我必須在數據庫中創建3個表。所以,我定義了表的列和行並執行SQLite命令。但是,當我嘗試向表中添加一些值時,會給我一個運行時錯誤。與此相反,當我只創建一個特定的表並在運行時爲其添加值時,事情似乎正常工作。下面是數據庫創建類別:無法在數據庫中創建多個表

public class StockDatabase extends SQLiteOpenHelper{ 


public static final String DATABASE_NAME="Accountancy"; 

public static final int DATABASE_VERSION=7; 

public static String createPurchaseTable= "CREATE TABLE stock (_id INTEGER PRIMARY KEY AUTOINCREMENT, item_name TEXT NOT NULL, quant INTEGER NOT NULL, Prate REAl NOT NULL, Srate REAL NOT NULL);"; 
public static String createSaleTable="CREATE TABLE i/o_register (_id INTEGER PRIMARY KEY AUTOINCREMENT, item_code INTEGER NOT NULL, quantity INTEGER NOT NULL, rate REAL NOT NULL);"; 
public static String createRegister="CREATE TABLE s/p_register (PartyName TEXT NOT NULL, range TEXT NOT NULL, date TEXT NOT NULL, type INTEGER NOT NULL);"; 


public StockDatabase(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    // TODO Auto-generated constructor stub 

} 

@Override 
public void onCreate(SQLiteDatabase db) { 
    // TODO Auto-generated method stub 
    db.execSQL(createPurchaseTable); 
    db.execSQL(createSaleTable); 
    db.execSQL(createRegister); 
} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // TODO Auto-generated method stub 
    db.execSQL("DROP TABLE IF EXISTS stock"); 
    db.execSQL("DROP TABLE IF EXISTS i/o_register"); 
    db.execSQL("DROP TABLE IF EXISTS s/p_register"); 
    onCreate(db); 
    } 

    } 

CASE:在數據庫中只創建「庫存」表時。 當我嘗試添加一些值到'股票'表的事情工作完美。

CASE:當在數據庫中創建3個表格 我嘗試將值添加到庫存表中,但它給了我一個nullPointerException。

+0

您可以添加包含錯誤的LogCat o/p嗎? –

回答

0

從表名稱中刪除/,或把表名總是在反引號:

sqlite> create table foo/bar(baz); 
Error: near "/": syntax error 
sqlite> create table `foo/bar`(baz); 
sqlite> 
+0

我做到了,但仍然沒有工作。是否我們一次只能在數據庫中創建一個表?因此,當我註釋掉其他2個表的db.exec()併爲1個表創建1個語句時。事情完美地工作 –

+0

「清除應用程序數據」在您的設備上,以便舊的數據庫首先被刪除,並更新的'onCreate()'被調用。 (對於發佈版本的數據庫更改,請使用其他答案中提到的版本機制。) – laalto

+0

對我來說太愚蠢了。我只在1個地方改變了具有'/'的表的名稱。然而,它的工作 –

0

嘗試在更改數據庫中的DATABASE_VERSION(即當前7)後創建新表。

編輯

現在嘗試用這種方式來創建一個表:

public class DatabaseManager { 
// the Activity or Application that is creating an object from this class. 
Context context; 

// a reference to the database used by this application/object 
private SQLiteDatabase db; 

// These constants are specific to the database. They should be 
// changed to suit your needs. 
private final String DB_NAME = "database_name_2"; 
private final int DB_VERSION = 8; 

// These constants are specific to the database table. They should be 
// changed to suit your needs. 
private final String TABLE_NAME = "database_table"; 
private final String TABLE_ROW_ID = "id"; 
private final String TABLE_ROW_ONE = "table_row_one"; 
private final String TABLE_ROW_TWO = "table_row_two"; 
private final String TABLE_ROW_THREE = "table_row_three"; 

public DatabaseManager(Context context) { 
    this.context = context; 

    // create or open the database 
    CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context); 
    this.db = helper.getWritableDatabase(); 

} 

/********************************************************************** 
* ADDING A ROW TO THE DATABASE TABLE 
* 
* This is an example of how to add a row to a database table using this 
* class. You should edit this method to suit your needs. 
* 
* the key is automatically assigned by the database 
* 
* @param rowStringOne 
*   the value for the row's first column 
* @param rowStringTwo 
*   the value for the row's second column 
*/ 
public void addRow(String rowStringOne, String rowStringTwo, String qty) { 
    // this is a key value pair holder used by android's SQLite functions 
    ContentValues values = new ContentValues(); 
    values.put(TABLE_ROW_ONE, rowStringOne); 
    values.put(TABLE_ROW_TWO, rowStringTwo); 
    values.put(TABLE_ROW_THREE, qty); 

    // ask the database object to insert the new data 
    try { 
     db.insert(TABLE_NAME, null, values); 
    } catch (Exception e) { 
     Log.e("DB ERROR", e.toString()); 
     e.printStackTrace(); 
    } 
} 

/********************************************************************** 
* DELETING A ROW FROM THE DATABASE TABLE 
* 
* This is an example of how to delete a row from a database table using 
* this class. In most cases, this method probably does not need to be 
* rewritten. 
* 
* @param rowID 
*   the SQLite database identifier for the row to delete. 
*/ 
public void deleteRow(long rowID) { 
    // ask the database manager to delete the row of given id 
    try { 
     db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null); 
    } catch (Exception e) { 
     Log.e("DB ERROR", e.toString()); 
     e.printStackTrace(); 
    } 
} 

/********************************************************************** 
* UPDATING A ROW IN THE DATABASE TABLE 
* 
* This is an example of how to update a row in the database table using 
* this class. You should edit this method to suit your needs. 
* 
* @param rowID 
*   the SQLite database identifier for the row to update. 
* @param rowStringOne 
*   the new value for the row's first column 
* @param rowStringTwo 
*   the new value for the row's second column 
*/ 
public void updateRow(long rowID, String rowStringOne, String rowStringTwo, 
     String qty) { 
    // this is a key value pair holder used by android's SQLite functions 
    ContentValues values = new ContentValues(); 
    values.put(TABLE_ROW_ONE, rowStringOne); 
    values.put(TABLE_ROW_TWO, rowStringTwo); 
    values.put(TABLE_ROW_THREE, qty); 

    // ask the database object to update the database row of given rowID 
    try { 
     db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null); 
    } catch (Exception e) { 
     Log.e("DB Error", e.toString()); 
     e.printStackTrace(); 
    } 
} 

/********************************************************************** 
* RETRIEVING A ROW FROM THE DATABASE TABLE 
* 
* This is an example of how to retrieve a row from a database table using 
* this class. You should edit this method to suit your needs. 
* 
* @param rowID 
*   the id of the row to retrieve 
* @return an array containing the data from the row 
*/ 
public ArrayList<Object> getRowAsArray(long rowID) { 
    // create an array list to store data from the database row. 
    // I would recommend creating a JavaBean compliant object 
    // to store this data instead. That way you can ensure 
    // data types are correct. 
    ArrayList<Object> rowArray = new ArrayList<Object>(); 
    Cursor cursor; 

    try { 
     // this is a database call that creates a "cursor" object. 
     // the cursor object store the information collected from the 
     // database and is used to iterate through the data. 
     cursor = db.query(TABLE_NAME, new String[] { TABLE_ROW_ID, 
       TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE }, 
       TABLE_ROW_ID + "=" + rowID, null, null, null, null, null); 

     // move the pointer to position zero in the cursor. 
     cursor.moveToFirst(); 

     // if there is data available after the cursor's pointer, add 
     // it to the ArrayList that will be returned by the method. 
     if (!cursor.isAfterLast()) { 
      do { 
       rowArray.add(cursor.getLong(0)); 
       rowArray.add(cursor.getString(1)); 
       rowArray.add(cursor.getString(2)); 
       rowArray.add(cursor.getString(3)); 
      } while (cursor.moveToNext()); 
     } 

     // let java know that you are through with the cursor. 
     cursor.close(); 
    } catch (SQLException e) { 
     Log.e("DB ERROR", e.toString()); 
     e.printStackTrace(); 
    } 

    // return the ArrayList containing the given row from the database. 
    return rowArray; 
} 

/********************************************************************** 
* RETRIEVING ALL ROWS FROM THE DATABASE TABLE 
* 
* This is an example of how to retrieve all data from a database table 
* using this class. You should edit this method to suit your needs. 
* 
* the key is automatically assigned by the database 
*/ 

public ArrayList<ArrayList<Object>> getAllRowsAsArrays() { 
    // create an ArrayList that will hold all of the data collected from 
    // the database. 
    ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>(); 

    // this is a database call that creates a "cursor" object. 
    // the cursor object store the information collected from the 
    // database and is used to iterate through the data. 
    Cursor cursor; 

    try { 
     // ask the database object to create the cursor. 
     cursor = db.query(TABLE_NAME, new String[] { TABLE_ROW_ID, 
       TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE }, null, 
       null, null, null, null); 

     // move the cursor's pointer to position zero. 
     cursor.moveToFirst(); 

     // if there is data after the current cursor position, add it 
     // to the ArrayList. 
     if (!cursor.isAfterLast()) { 
      do { 
       ArrayList<Object> dataList = new ArrayList<Object>(); 

       dataList.add(cursor.getLong(0)); 
       dataList.add(cursor.getString(1)); 
       dataList.add(cursor.getString(2)); 
       dataList.add(cursor.getString(3)); 

       dataArrays.add(dataList); 
      } 
      // move the cursor's pointer up one position. 
      while (cursor.moveToNext()); 
     } 
    } catch (SQLException e) { 
     Log.e("DB Error", e.toString()); 
     e.printStackTrace(); 
    } 

    // return the ArrayList that holds the data collected from 
    // the database. 
    return dataArrays; 
} 

/********************************************************************** 
* THIS IS THE BEGINNING OF THE INTERNAL SQLiteOpenHelper SUBCLASS. 
* 
* I MADE THIS CLASS INTERNAL SO I CAN COPY A SINGLE FILE TO NEW APPS AND 
* MODIFYING IT - ACHIEVING DATABASE FUNCTIONALITY. ALSO, THIS WAY I DO NOT 
* HAVE TO SHARE CONSTANTS BETWEEN TWO FILES AND CAN INSTEAD MAKE THEM 
* PRIVATE AND/OR NON-STATIC. HOWEVER, I THINK THE INDUSTRY STANDARD IS TO 
* KEEP THIS CLASS IN A SEPARATE FILE. 
*********************************************************************/ 

/** 
* This class is designed to check if there is a database that currently 
* exists for the given program. If the database does not exist, it creates 
* one. After the class ensures that the database exists, this class will 
* open the database for use. Most of this functionality will be handled by 
* the SQLiteOpenHelper parent class. The purpose of extending this class is 
* to tell the class how to create (or update) the database. 
* 
* @author Randall Mitchell 
* 
*/ 
private class CustomSQLiteOpenHelper extends SQLiteOpenHelper { 
    public CustomSQLiteOpenHelper(Context context) { 
     super(context, DB_NAME, null, DB_VERSION); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
     // This string is used to create the database. It should 
     // be changed to suit your needs. 
     String newTableQueryString = "create table " + TABLE_NAME + " (" 
       + TABLE_ROW_ID 
       + " integer primary key autoincrement not null," 
       + TABLE_ROW_ONE + " text," + TABLE_ROW_TWO + " text" 
       + TABLE_ROW_THREE + " text" + ");"; 

     // execute the query string to the database. 
     db.execSQL(newTableQueryString); 

     String newTableQueryString2 = "alter table " + TABLE_NAME 
       + " ADD COLUMN " + TABLE_ROW_THREE + " text"; 
     // execute the query string to the database. 
     db.execSQL(newTableQueryString2); 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 

     // NOTHING TO DO HERE. THIS IS THE ORIGINAL DATABASE VERSION. 
     // OTHERWISE, YOU WOULD SPECIFIY HOW TO UPGRADE THE DATABASE. 
    } 
} 
    } 
+0

是的,我已經這樣做了7次,以解決這個問題 –

+0

我編輯了我的答案 – Avijit

0

卡蘭我beleive你提供我的表名/ o_register創造問題只是改變表名和做在表名中不包含'/',那麼一切都會正常工作。 你的創建查詢也沒有在Sqlite for windows上運行。

0

增量你的數據庫版本。始終有效。

+0

幾次。您如何看待我的版本7 –

+0

您可能會使用Web上發佈的項目中的代碼的某些部分。它的db版本一開始是7。 – Tugrul