朋友您好我是通过编程方式在我的应用程序中创建SQLite数据库。
这是我的代码:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION =3;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_EMAIL = "email";
private static final String KEY_ADD = "address";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT," + KEY_EMAIL + " TEXT,"+ KEY_ADD + " TEXT )";
db.execSQL(CREATE_CONTACTS_TABLE);
System.out.println("Create");
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// If you need to add a column
if (newVersion > oldVersion) {
onCreate(db);
db.execSQL("ALTER TABLE contacts ADD COLUMN gender TEXT;");
}
// Create tables again
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
public void Add_Contact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
values.put(KEY_EMAIL, contact.getEmail()); // Contact Email
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO, KEY_EMAIL }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3));
// return contact
cursor.close();
db.close();
return contact;
}
// Getting All Contacts
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contact.setEmail(cursor.getString(3));
// Adding contact to list
contact_list.add(contact);
} while (cursor.moveToNext());
}
// return contact list
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
// Updating single contact
public int Update_Contact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
values.put(KEY_EMAIL, contact.getEmail());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void Delete_Contact(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(id) });
db.close();
}
// Getting contacts Count
public int Get_Total_Contacts() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
问题是当我将数据库版本从1升级到2时,我的数据库中添加了新列,但我的旧数据被删除了,那么我该如何解决这个问题呢?你的所有建议都很明显。
修改
Ya为 Rajesh Jadav 和 Amy 的解决方案工作但是当我将版本2更改为3时,它会给出错误,例如重复的列性别。我的功能如下
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
//db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE contacts ADD COLUMN gender TEXT;");
db.execSQL("ALTER TABLE contacts ADD COLUMN dob TEXT;");
}
}
但是当我对第db.execSQL("ALTER TABLE contacts ADD COLUMN gender TEXT;");
行进行评论时,它的工作正常,那么每当我升级数据库版本时,有什么正确的方法可以在那个地方进行评论吗?
答案 0 :(得分:1)
试试这个。
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE contacts ADD COLUMN gender TEXT;");
}
// Create tables again
}
您已在onUpgrade中调用 db.execSQL(“DROP TABLE IF EXISTS”+ TABLE_CONTACTS); 。所以它将清除所有现有数据。
如果你必须保留旧数据删除该查询。
修改强>
重复列问题有两种解决方案。
<强>首先强>
你可以通过try catch语句包围。
try{
db.execSQL("ALTER TABLE contacts ADD COLUMN gender TEXT;");
db.execSQL("ALTER TABLE contacts ADD COLUMN dob TEXT;");
}catch(Exception e){
}
<强>第二强>
您可以使用此方法检查表中是否已存在列。
private boolean existsColumnInTable(SQLiteDatabase inDatabase, String inTable, String columnToCheck) {
Cursor mCursor = null;
try {
// Query 1 row
mCursor = inDatabase.rawQuery("SELECT * FROM " + inTable + " LIMIT 0", null);
// getColumnIndex() gives us the index (0 to ...) of the column - otherwise we get a -1
if (mCursor.getColumnIndex(columnToCheck) != -1)
return true;
else
return false;
} catch (Exception Exp) {
// Something went wrong. Missing the database? The table?
Log.d("... - existsColumnInTable", "When checking whether a column exists in the table, an error occurred: " + Exp.getMessage());
return false;
} finally {
if (mCursor != null) mCursor.close();
}
}
只需致电:
boolean gender_column_exist = existsColumnInTable(db,"contacts","gender");
if(!gender_column_exist){
db.execSQL("ALTER TABLE contacts ADD COLUMN gender TEXT;");
}
boolean dob_column_exist = existsColumnInTable(db,"contacts","dob");
if(!dob_column_exist){
db.execSQL("ALTER TABLE contacts ADD COLUMN dob TEXT;");
}
希望这有帮助!
答案 1 :(得分:1)
试试这个:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
// db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); //Remove This Line
// If you need to add a column
if (newVersion > oldVersion) {
onCreate(db);
db.execSQL("ALTER TABLE contacts ADD COLUMN gender TEXT;");
}
}
从onUpgrade()方法中删除或注释第一行。它会删除旧表和数据。