繁体   English   中英

SQLite中的多个数据库表

[英]Multiple database tables in SQLite

我是Android和SQLite的新手。 我试图在数据库中创建多个表,首先在其中将电子邮件详细信息保存在数据库中,然后通过该保存的电子邮件从服务器中检索电子邮件。 当我尝试将电子邮件数据保存到第二个数据库表时,它将引发空指针异常。 这是因为Sqlitedatabase db = this.writeabledatabase; 语句alwasy变为null,这意味着数据库无法获取路径。 这是我的代码:

  package com.elevenvalues.baig.db2listviewupdatedeleteinsert;
 import android.content.ContentValues;
 import android.content.Context;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;

 import java.sql.SQLException;


 public class DbHelper extends SQLiteOpenHelper {


 //  table name
 public static final String EMAIL_INSERT_TABLE = "EmailInsertDetail";
 public static final String EMAIL_LOG = "EmailLog";
 // Database Version
 private static final int DATABASE_VERSION = 1;

 // Database Name
 public static String DATABASE_NAME = "My database";

 public static final String KEY_USERNAME = "username";
 public static final String KEY_EMAIL = "email";
 public static final String KEY_PASSWORD = "password";
 public static final String KEY_SERVER = "server";
 public static final String KEY_PORT = "port";
 public static final String KEY_SECURITY_TYPE = "securityType";
 public static final String KEY_ACTIVE_TIME = "activeTime";
 public static final String KEY_ID = "id";

 public static final String KEY_ROWID = "id";
 public static final String KEY_FROM = "froom";
 public static final String KEY_TO = "too";
 public static final String KEY_MESSAGE_BODY = "messagebody";


 SQLiteDatabase db;
 private boolean isUpdate;
 String id;



 public DbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);


 }

 @Override
 public void onCreate(SQLiteDatabase db) {


    String CREATE_TABLE = "CREATE TABLE " + EMAIL_INSERT_TABLE + " (" + KEY_ID + " INTEGER PRIMARY KEY, "
            + KEY_USERNAME + " TEXT, " + KEY_EMAIL + " TEXT," + KEY_PASSWORD + " TEXT," + KEY_SERVER + " TEXT," +
            KEY_PORT + " TEXT," + KEY_SECURITY_TYPE + " TEXT," + KEY_ACTIVE_TIME + " TEXT);";


    String CREATE_SERVER_DATABASE = "CREATE TABLE " + EMAIL_LOG + " (" + KEY_ROWID + " INTEGER PRIMARY KEY, "
            + KEY_TO + " TEXT, " + KEY_FROM + " TEXT," + KEY_MESSAGE_BODY + " TEXT);";



    db.execSQL(CREATE_SERVER_DATABASE);
    db.execSQL(CREATE_TABLE);

 }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + EMAIL_INSERT_TABLE);

    db.execSQL("DROP TABLE IF EXISTS " + EMAIL_LOG);

    // create new tables
    onCreate(db);

 }

  void EmailReadDataInsert(String from, String too, String messageBody) {


    db=this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(DbHelper.KEY_FROM, from);
    cv.put(DbHelper.KEY_TO, too);
    cv.put(DbHelper.KEY_MESSAGE_BODY, messageBody);
    // Inserting Row
    db.insert(EMAIL_LOG, null, cv);

    }


  /**
  * save data into SQLite
  */
  public void AddEmailData(String username,String email,String password,String server,String port,String securityType,
  String   activeTime) {
    db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(DbHelper.KEY_USERNAME, username);
    values.put(DbHelper.KEY_EMAIL, email);
    values.put(DbHelper.KEY_PASSWORD, password);
    values.put(DbHelper.KEY_SERVER, server);
    values.put(DbHelper.KEY_PORT, port);
    values.put(DbHelper.KEY_SECURITY_TYPE, securityType);
    values.put(DbHelper.KEY_ACTIVE_TIME, activeTime);

    if (isUpdate) {
        //update database with new data
        db.update(DbHelper.EMAIL_INSERT_TABLE, values, DbHelper.KEY_ID + "=" + id, null);
    } else {
        //insert data into database
        db.insert(DbHelper.EMAIL_INSERT_TABLE, null, values);
    }
    //close database
    db.close();

  } 


  //---opens the database---
  public DbHelper open() throws SQLException
  {
    db = this.getWritableDatabase();
    return this;
  }


  //---closes the database---
  public void close()
  {
    this.close();
 }

 }

db变为null的此方法中会发生问题:

 void EmailReadDataInsert(String from, String too, String messageBody) {


    db=this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(DbHelper.KEY_FROM, from);
    cv.put(DbHelper.KEY_TO, too);
    cv.put(DbHelper.KEY_MESSAGE_BODY, messageBody);
    // Inserting Row
    db.insert(EMAIL_LOG, null, cv);

    }

我该如何解决我的问题? 有什么建议么?

如果您试图在一个数据库中创建多个表,则不必总是创建一个新数据库。 您需要对用于管理数据库中条目的类进行一些微调,以提供两个表。 尝试添加以下代码:

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

public class Database {
    static final String databaseName = "My database";
    static final int databaseVersion = 0;
    static final String rowId = “id”; 
    static final String rowUsername = “username”; 
    static final String rowEmail = “email”; 
    static final String rowPassword = "password";
    static final String rowServer = “server”;
    static final String rowPort = "port";
    static final String rowSecurityType = "securityType";
    static final String rowActiveTime = "activeTime";

    static final String emailTable = "EmailInsertDetail";
    static final String logTable = "EmailLog";

    static final String rowFrom = "from";
    static final String rowTo = "to";
    static final String rowMessage = "message";
    final Context context;

    SqlLiteDatabase database;
    DatabaseHelper helper;

    public Database(Context context) {
        this.context = context;
        this.helper = new DatabaseHelper(context);
    }

    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, databaseName, null, databaseVersion); 
        }

        @Override
        public void onCreate(SQLiteDatabase database) {
            try {
                database.execSQL("CREATE TABLE IF NOT EXISTS " + emailTable);
                database.execSQL("CREATE TABLE IF NOT EXISTS " + logTable);
            } catch (SQLException ex) {
                  ex.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
            Log.w("Database", “Upgrading database from version “ + oldVersion + “ to “ + newVersion + “, which will destroy all old data”);
            db.execSQL(“DROP TABLE IF EXISTS " + emailTable + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT, password TEXT, server TEXT, port TEXT, securityType TEXT, activeTime TEXT)");
            db.execSQL("DROP TABLE IF EXISTS " + logTable + " (id INTEGER PRIMARY KEY AUTOINCREMENT, from TEXT, to TEXT, message TEXT)");
            onCreate(database);
         }
    }

    public Database open() throws SQLException {
        this.database = DatabaseHelper.getWritableDatabase();
        return this;
    }

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

     public long insertEmail(String username, String email, String password, String server, String port, String securityType, String activeTime) {
         ContentValues contentValues = new ContentValues();

         contentValues.put(rowUsername, username);
         contentValues.put(rowEmail, email);
         contentValues.put(rowPassword, password);
         contentValues.put(rowServer, server);
         contentValues.put(rowPort, port);
         contentValues.put(rowSecurityType, securityType);
         contentValues.put(rowActiveTime, activeTime);

         return database.insert(emailTable, null, contentValues);
     }

     public long insertData(String from, String to, String message) {
         ContentValues contentValues = new ContentValues();

         contentValues.put(rowFrom, from);
         contentValues.put(rowTo, to);
         contentValues.put(rowMessage, message);

         return database.insert(logTable, null, contentValues);
     }

     public boolean updateEmail(long id, String username, String email, String password, String server, String port, String securityType, String activeTime) {
         ContentValues contentValues = new ContentValues();

         contentValues.put(rowUsername, username);
         contentValues.put(rowEmail, email);
         contentValues.put(rowPassword, password);
         contentValues.put(rowServer, server);
         contentValues.put(rowPort, port);
         contentValues.put(rowSecurityType, securityType);
         contentValues.put(rowActiveTime, activeTime);

         return database.update(emailTable, contentValues, rowId + "=" + id, null) > 0;
     }

     public boolean updateEmail(long id, String from, String to, String message) {
         ContentValues contentValues = new ContentValues();

         contentValues.put(rowFrom, from);
         contentValues.put(rowTo, to);
         contentValues.put(rowMessage, message);

         return database.update(logTable, contentValues, rowId + "=" + id, null) > 0;
     }

     public Cursor getAllEmails() {
         return database.query(emailTable, new String[] {rowId, rowUsername, rowEmail, rowPassword, rowServer, rowPort, rowSecurityType, rowActiveTime}, null, null, null, null, null);
     }

     public Cursor getAllData() {
         return database.query(logTable, new String[] {rowId, rowFrom, rowTo, rowMessage}, null, null, null, null, null);
     }

     public Cursor getEmail(long id) throws SQLException {
         Cursor cursor = db.query(true, emailTable, new String[] {rowId, rowUsername, rowEmail, rowPassword, rowServer, rowPort, rowSecurityType, rowActiveTime}, rowId + “=” + id, null, null, null, null, null);

         if (cursor != null) {
             cursor.moveToFirst();
         }
         return cursor;
     }

     public Cursor getData(long id) throws SQLException {
         Cursor cursor = db.query(true, logTable, new String[] {rowId, rowFrom, rowTo, rowMessage}, rowId + “=” + id, null, null, null, null, null);

         if (cursor != null) {
             cursor.moveToFirst();
         }
         return cursor;
     }
}

在要插入或检索数据的活动或类中,键入:

Database database = new Database(context);
database.open();

// To insert whatever data you want
long insert = database.insertEmail(parametres go in here);

// To update whatever data you want
if (database.updateEmail(the parametres))
    // more code to be executed

// To retrieve all items in a table
Cursor cursor = database.getAllEmails();

if (cursor.moveToFirst()) {
    do {
        Toast.makeText(this, "Id: " + cursor.getInt(0) + " Email: " + cursor.getString(2), Toast.LENGTH_SHORT).show();
    } while (cursor.moveToNext();
}

// To retrieve a certain item
Cursor cursor = database.getEmail(the id);
    Toast.makeText(this, "Id: " + cursor.getInt(0) + " From: " + cursor.getString(1), Toast.LENGTH_SHORT).show();
if (cursor.moveToFirst()) {

}

database.close();

请记住用thisgetContext()Context变量替换context 请记住用自己的代码替换Toast语句。 如果仍然有问题,请务必参考这本电子书,该书对您有帮助,或者在下面留下一些评论。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM