Я совершенно новичок в sqlite и android. У меня есть следующая таблица, в которую я ввожу информацию о пользователе:
private static final String CREATE_TABLE_USERS = "CREATE TABLE "
+ TABLE_USER + "(" + KEY_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+ KEY_TAG + " TEXT,"
+ KEY_FIRSTNAME + " TEXT," + KEY_LASTNAME + " TEXT," + KEY_DOB + " TEXT," + KEY_GENDER + " TEXT,"
+ KEY_JOB + " TEXT );";
И еще одну таблицу для входящих данных, содержащую (TAG, Дата и время):
private static final String CREATE_TABLE_LOG = "CREATE TABLE "
+ TABLE_LOG + "(" + KEY_LOG_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+ KEY_TAG + " TEXT,"
+ KEY_DATE + " TEXT," + KEY_TIME + " TEXT );";
Все, что я хочу, это найдите входящий «TAG» в TABLE_USER и получите «FirstName» и «LastName» из TABLE_USER и поместите эти плюс «Date» и «Time» в третью таблицу следующим образом:
private static final String CREATE_TABLE_MAIN= "CREATE TABLE "
+ TABLE_MAIN + "(" + KEY_MAIN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+ KEY_TAG + " TEXT,"
+ KEY_FIRSTNAME + " TEXT," + KEY_LASTNAME + " TEXT,"+ KEY_DATE + " TEXT," + KEY_TIME + " TEXT );";
Какой запрос лучше чтобы это произошло?
И это код класса DatabaseHelper. Код:
public class DatabaseHelper extends SQLiteOpenHelper {
public static String DATABASE_NAME = "RFID_Database.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_USER = "TABLE_USER";
private static final String TABLE_LOG = "TABLE_LOG";
private static final String TABLE_MAIN = "TABLE_MAIN";
private static final String KEY_USER_ID = "user_id";
private static final String KEY_LOG_ID = "log_id";
private static final String KEY_MAIN_ID = "main_id";
private static final String KEY_FIRSTNAME = "FirstName";
private static final String KEY_LASTNAME = "LastName";
private static final String KEY_TAG = "TAG";
private static final String KEY_DOB = "DOB";
private static final String KEY_GENDER = "SEX";
private static final String KEY_JOB = "JOB";
private static final String KEY_DATE = "DATE";
private static final String KEY_TIME = "TIME";
private Context mContext;
SQLiteDatabase database = this.getWritableDatabase();
private static final String CREATE_TABLE_USERS = "CREATE TABLE "
+ TABLE_USER + "(" + KEY_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+ KEY_TAG + " TEXT,"
+ KEY_FIRSTNAME + " TEXT," + KEY_LASTNAME + " TEXT," + KEY_DOB + " TEXT," + KEY_GENDER + " TEXT,"
+ KEY_JOB + " TEXT );";
private static final String CREATE_TABLE_LOG = "CREATE TABLE "
+ TABLE_LOG + "(" + KEY_LOG_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+ KEY_TAG + " TEXT,"
+ KEY_DATE + " TEXT," + KEY_TIME + " TEXT );";
private static final String CREATE_TABLE_MAIN= "CREATE TABLE "
+ TABLE_MAIN + "(" + KEY_MAIN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"+ KEY_TAG + " TEXT,"
+ KEY_FIRSTNAME + " TEXT," + KEY_LASTNAME + " TEXT,"+ KEY_DATE + " TEXT," + KEY_TIME + " TEXT );";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_USERS);
db.execSQL(CREATE_TABLE_LOG);
db.execSQL(CREATE_TABLE_MAIN);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS '" + TABLE_USER + "'");
db.execSQL("DROP TABLE IF EXISTS '" + TABLE_LOG + "'");
db.execSQL("DROP TABLE IF EXISTS '" + TABLE_MAIN + "'");
onCreate(db);
}
public void addUser(String tag, String FirstName, String LastName, String Dob, String Sex, String Job ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FIRSTNAME, FirstName);
values.put(KEY_LASTNAME, LastName);
values.put(KEY_TAG, tag);
values.put(KEY_DOB, Dob);
values.put(KEY_GENDER, Sex);
values.put(KEY_JOB, Job);
db.insertWithOnConflict(TABLE_USER, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
public void addLog(String Tag, String Date_, String Time_) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TAG, Tag);
values.put(KEY_DATE, Date_);
values.put(KEY_TIME, Time_);
db.insertWithOnConflict(TABLE_LOG, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
public void addMain(String tag, String FirstName, String LastName, String Date, String Time) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FIRSTNAME, FirstName);
values.put(KEY_LASTNAME, LastName);
values.put(KEY_TAG, tag);
values.put(KEY_DATE, Date);
values.put(KEY_TIME, Time);
db.insertWithOnConflict(TABLE_MAIN, null, values, SQLiteDatabase.CONFLICT_IGNORE);
}
public ArrayList<UserModel> getAllUsers() {
ArrayList<UserModel> userModelArrayList = new ArrayList<UserModel>();
String selectQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
UserModel userModel = new UserModel();
userModel.setId(c.getInt(c.getColumnIndex(KEY_USER_ID)));
userModel.setTag(c.getString(c.getColumnIndex(KEY_TAG)));
userModel.setFirstName(c.getString(c.getColumnIndex(KEY_FIRSTNAME)));
userModel.setLastName(c.getString(c.getColumnIndex(KEY_LASTNAME)));
userModel.setDOB(c.getString(c.getColumnIndex(KEY_DOB)));
userModel.setSex(c.getString(c.getColumnIndex(KEY_GENDER)));
userModel.setJob(c.getString(c.getColumnIndex(KEY_JOB)));
userModelArrayList.add(userModel);
} while (c.moveToNext());
}
return userModelArrayList;
}
public ArrayList<UserModel> Display_Logs() {
ArrayList<UserModel> userModelArrayList = new ArrayList<UserModel>();
String selectQuery = "SELECT * FROM " + TABLE_LOG;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
UserModel userModel = new UserModel();
userModel.setId(c.getInt(c.getColumnIndex(KEY_LOG_ID)));
userModel.setTag(c.getString(c.getColumnIndex(KEY_TAG)));
userModel.setDate_(c.getString(c.getColumnIndex(KEY_DATE)));
userModel.setTime_(c.getString(c.getColumnIndex(KEY_TIME)));
userModelArrayList.add(userModel);
} while (c.moveToNext());
}
return userModelArrayList;
}
public ArrayList<UserModel> getMainLogs() {
ArrayList<UserModel> userModelArrayList = new ArrayList<UserModel>();
String selectQuery = "SELECT * FROM " + TABLE_MAIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
UserModel userModel = new UserModel();
userModel.setId(c.getInt(c.getColumnIndex(KEY_MAIN_ID)));
userModel.setTag(c.getString(c.getColumnIndex(KEY_TAG)));
userModel.setFirstName(c.getString(c.getColumnIndex(KEY_FIRSTNAME)));
userModel.setLastName(c.getString(c.getColumnIndex(KEY_LASTNAME)));
userModel.setDate_(c.getString(c.getColumnIndex(KEY_DATE)));
userModel.setTime_(c.getString(c.getColumnIndex(KEY_TIME)));
userModelArrayList.add(userModel);
} while (c.moveToNext());
}
return userModelArrayList;
}
public void UpdateUser(int id, String User_ID, String FirstName, String LastName, String Dob,
String Sex, String Job ) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TAG, User_ID);
values.put(KEY_FIRSTNAME, FirstName);
values.put(KEY_LASTNAME, LastName);
values.put(KEY_DOB, Dob);
values.put(KEY_GENDER, Sex);
values.put(KEY_JOB, Job);
db.update(TABLE_USER, values, KEY_USER_ID + " = ?", new String[]{String.valueOf(id)});
}
public void DeleteUser(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_USER, KEY_USER_ID + " = ?",new String[]{String.valueOf(id)});
}
public void backup(String outFileName) {
//database path
final String inFileName = mContext.getDatabasePath(DATABASE_NAME).toString();
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(mContext, "Backup Completed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, "Unable to backup database. Retry", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
public void importDB(String inFileName) {
final String outFileName = mContext.getDatabasePath(DATABASE_NAME).toString();
try {
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
Toast.makeText(mContext, "Import Completed", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(mContext, "Unable to import database. Retry", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
public void Delete_All(String Table_Name){
SQLiteDatabase sql=this.getWritableDatabase();
sql.execSQL("delete from "+ Table_Name);
}
public Cursor Search(String tag){
SQLiteDatabase database = this.getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM TABLE_USER WHERE TAG = '"+tag+"'", null);
return cursor;
}
public String getUserName(String tag) {
Cursor cursor = null;
String firstName = "";
String lastName = "";
try {
cursor = database.rawQuery("SELECT * FROM " + TABLE_USER + " WHERE "+ KEY_TAG +"=?", new String[] {tag});
if(cursor.getCount() > 0) {
cursor.moveToFirst();
firstName= cursor.getString(cursor.getColumnIndex(KEY_FIRSTNAME));
lastName= cursor.getString(cursor.getColumnIndex(KEY_LASTNAME));
}
return firstName;
}finally {
cursor.close();
}
}
}