使用起来超简单 :
ThrustDBHelper thrustDBHelper = new ThrustDBHelper(this);
//添加一条数据
thrustDBHelper.addDataBase(new ThrustData));
//查询所有数据
List list<thrust> = thrustDBHelper.findAll(ThrustData.class)
具体用法 自己慢慢看 , 很简单的 不懂得 可以加群来问我qq群: 164603384
package com.example.ndkreadfpga.db;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* 数据库管理工具
*
* @author Raul
*
*/
public abstract class BaseDBHelper<T> {
// 数据库名
public static String DATABASE_NAME = "TABLE_Data.db";
// 数据库版本
private static int DATABASE_VERSION = 1;
public static final String TEST_DATA = "TEST_DATA"; // 坡度
/********************************************** 创建表信息 **************************************/
private final Context context;
private DatabaseHelper DBHelper;
public SQLiteDatabase db;
/**
* 构造方法
*
* @param ctx
*/
public BaseDBHelper(Context ctx,String dbName) {
this.context = ctx;
// // 得到版本值ֵ
DATABASE_VERSION = getCurrentVersion(context);
DATABASE_NAME = dbName;
DBHelper = new DatabaseHelper(context);
}
@SuppressWarnings("finally")
private static int getCurrentVersion(Context context) {
int verCordeOld = 0;
try {
// 获取应用信息
PackageInfo info = context.getPackageManager().getPackageInfo(
context.getPackageName(), 0);
// 得到应用版本�?
verCordeOld = info.versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
} finally {
return verCordeOld;
}
}
public abstract String createTab();
private class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
/**
* 在创建数据库连接时, 创建数据库表。
*/
String sqlString = createTab();
Log.e("SQL", sqlString);
db.execSQL(sqlString);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("old version: " + oldVersion);
System.out.println("new version: " + newVersion);
db.execSQL("DROP TABLE IF EXISTS " + TEST_DATA);
this.onCreate(db);
}
}
/**
* 打开一个数据库连接。
*
* @return
* @throws SQLException
*/
public BaseDBHelper open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
/**
* 关闭数据库连接
*/
public void close() {
DBHelper.close();
}
/**
*插入操作。
*
* @param entity
* @param initialValues
* @return
*/
public long insert(String entity, ContentValues initialValues) {
return db.insert(entity, null, initialValues);
}
/**
*获取数据库表信息。
*
* @param entity
* @param cols
* @param selection
* @return
*/
public Cursor get(String entity, String[] cols, String selection) {
Cursor mCursor = db.query(true, entity, cols, selection, null, null,
null, null, null);
return mCursor;
}
/**
* 获取数据库表信息。
*
* @param entity
* @param cols
* @param selection
* @param order
* @return
*/
public Cursor get(String entity, String[] cols, String selection,
String order) {
Cursor mCursor = db.query(true, entity, cols, selection, null, null,
null, order, null);
return mCursor;
}
/**
* 更新数据库
*
* @param entity
* @param selection
* @param initialValues
* @return
*/
public boolean update(String entity, ContentValues initialValues,
String selection) {
return db.update(entity, initialValues, selection, null) > 0;
}
/**
* 清空数据库表。
*
* @param entity
*/
public void delete(String entity) {
db.delete(entity, null, null);
}
/**
* 清空数据库表。
*
* @param entity
* @param selection
*/
public void delete(String entity, String selection) {
db.delete(entity, selection, null);
}
public void drop(String[] entity) {
db.execSQL("DROP TABLE IF EXISTS diary");
}
/**
* @return the db
*/
public SQLiteDatabase getDb() {
return db;
}
/**
* Add a data
* @param entity
* @return
*/
public long addDataBase(T entity) {
SQLiteDatabase sqLiteDatabase = this.open().getDb();
ContentValues cValues = new ContentValues();
try {
Field[] fs = entity.getClass().getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field field = fs[i];
field.setAccessible(true);
Object val = null; //
if (field.get(entity) != null)
val = field.get(entity);
if (val != null && !val.equals("")
&& !field.getName().endsWith("Id")) {
String type = field.getType().getName();// 得到此属性的类型
if (type.contains("String")) {
cValues.put(field.getName(), String.valueOf(val));
} else if (type.contains("Integer") || type.contains("int")) {
cValues.put(field.getName(), Integer.parseInt(String.valueOf(val)));
}else if (type.contains("long") || type.contains("Long")){
cValues.put(field.getName(), Long.parseLong(String.valueOf(val)));
}else if (type.contains("float") || type.contains("Float")){
cValues.put(field.getName(), Float.parseFloat(String.valueOf(val)));
}else {
cValues.put(field.getName(), String.valueOf(val));
}
}
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long lg = sqLiteDatabase.insert(entity.getClass().getSimpleName(), null,
cValues);//
Log.e("SQL", lg+"");
sqLiteDatabase.close();
return lg;
}
/**
*
* According to the entity object delete data
*
* @param entity
* @return
*/
public int deleteByOne(T entity) {
int result = -1;
db = open().getDb();
try {
Field[] fs = entity.getClass().getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
f.setAccessible(true); // 设置些属性是可以访问�?
String ss = fs[i].getName();
int val = 0;
if (ss.endsWith("Id")) {
if (f.get(entity) != null)
val = (Integer) f.get(entity);
if (val != 0) {
String whereClause = ss + "=?";// 删除的条�?
String[] whereArgs = { val + "" };// 删除的条件参�?
result = db.delete(entity.getClass().getSimpleName(),
whereClause, whereArgs);// 执行删除
db.close();
break;
}
}
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
/**
* According to the Class(Table Name) object query all the data
*
* @param entity
* @return
*/
public List<T> findAll(Class<T> entity) {
List<T> tables = new ArrayList<T>();
db = open().getDb();
try {
String sqlString = "select * from " + entity.getSimpleName();
Cursor c = db.rawQuery(sqlString, null);
// Cursor c = database.query(cla.getSimpleName(), null, null, null,
// null, null, null);// 查询并获得游�?
tables = getList(c,entity);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return tables;
}
public List<T> getList(Cursor c,Class<T> entity) throws InstantiationException,
IllegalAccessException {
// TODO Auto-generated method stub
List<T> tables = new ArrayList<T>();
T taT = null;
Field[] fs = entity.getDeclaredFields();
while (c.moveToNext()) {
taT = (T) entity.newInstance();
for (int i = 0; i < fs.length; i++) {
Field field = fs[i];
field.setAccessible(true);
String type = field.getType().getName();// 得到此属性的类型
if (type.contains("String")) {
String nameString = field.getName();
String valueString = c.getString(c
.getColumnIndex(nameString));
field.set(taT, valueString);
} else if (type.contains("Integer") || type.contains("int")) {
String nameString = field.getName();
int valueString = c.getInt(c.getColumnIndex(nameString));
field.set(taT, valueString);
}else if (type.contains("long") || type.contains("Long")){
String nameString = field.getName();
long valueString = c.getLong(c.getColumnIndex(nameString));
field.set(taT, valueString);
}else if (type.contains("float") || type.contains("Float")){
String nameString = field.getName();
float valueString = c.getFloat(c.getColumnIndex(nameString));
field.set(taT, valueString);
}else {
String nameString = field.getName();
String valueString = c.getString(c
.getColumnIndex(nameString));
field.set(taT, valueString);
}
}
tables.add(taT);
}
return tables;
}
}
package com.example.ndkreadfpga.db;
import java.util.ArrayList; import java.util.List;
import android.R.integer; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase;
import com.example.ndkreadfpga.entity.DataEntity; import com.example.ndkreadfpga.entity.OriginalData; import com.example.ndkreadfpga.entity.ThrustData;
public class ThrustDBHelper extends BaseDBHelper<ThrustData> {
public static final String TABLE_NAME = ThrustData.class.getSimpleName(); private SQLiteDatabase sqLiteDatabase;
public ThrustDBHelper(Context ctx) { super(ctx,TABLE_NAME); // TODO Auto-generated constructor stub //重新创建数据库 不然第二个表创建不出来 }
@Override public String createTab() { // TODO Auto-generated method stub String sqlString = "create table " + TABLE_NAME + "(thrustId integer primary key autoincrement , " + "steelNum varchar(10), " + "fromNum varchar(10) , " + "toNum varchar(10) , " + "thrust integer," + "isUnusual integer," + "date long);"; return sqlString; } /** * 根据钢轨编号查数据 * * @param steelNum * * @throws IllegalAccessException * @throws InstantiationException */ public List<ThrustData> selectBySteelNum(String steelNum){ // TODO Auto-generated method stub try { sqLiteDatabase = open().getDb(); // select * from person order by id String sql = "select * from " + TABLE_NAME + " where steelNum = ?"; String[] selectionArgs = { steelNum }; Cursor cursor = sqLiteDatabase.rawQuery(sql, selectionArgs); return getList(cursor, ThrustData.class); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return new ArrayList<ThrustData>();
} /** * 根据时间查数据 * * @param steelNum * * @throws IllegalAccessException * @throws InstantiationException */ public List<ThrustData> selectBySteelNumByDate(String date){ // TODO Auto-generated method stub try { sqLiteDatabase = open().getDb(); // select * from person order by id String sql = "select * from " + TABLE_NAME + " where date = ?"; String[] selectionArgs = { date }; Cursor cursor = sqLiteDatabase.rawQuery(sql, selectionArgs); return getList(cursor, ThrustData.class); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return new ArrayList<ThrustData>();
} /** * 根据钢轨编号和日期查数据 * @param steelNum * @param date * @return */ public List<ThrustData> selectBySteelNum(String steelNum,String date){ // TODO Auto-generated method stub try { sqLiteDatabase = open().getDb(); // select * from person order by id String sql = "select * from " + TABLE_NAME + " where steelNum = ? and date = ?"; String[] selectionArgs = { steelNum ,date}; Cursor cursor = sqLiteDatabase.rawQuery(sql, selectionArgs); return getList(cursor, ThrustData.class); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return new ArrayList<ThrustData>();
} /** * 根据钢轨异常和日期查数据 * @param steelNum * @param date * @return */ public List<ThrustData> selectBySteelNumByIsUnusual(String isUnusual,String date){ // TODO Auto-generated method stub try { sqLiteDatabase = open().getDb(); // select * from person order by id String sql = "select * from " + TABLE_NAME + " where isUnusual = ? and date = ?"; String[] selectionArgs = { isUnusual ,date}; Cursor cursor = sqLiteDatabase.rawQuery(sql, selectionArgs); return getList(cursor, ThrustData.class); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return new ArrayList<ThrustData>();
} /** * 根据钢轨编号,是否异常 和日期查数据 * @param steelNum * @param date * @return */ public List<ThrustData> selectBySteelNum(String steelNum,String date,String isUnusual){ // TODO Auto-generated method stub try { sqLiteDatabase = open().getDb(); // select * from person order by id String sql = "select * from " + TABLE_NAME + " where steelNum = ? and date = ? and isUnusual = ?"; String[] selectionArgs = { steelNum ,date,isUnusual+""}; Cursor cursor = sqLiteDatabase.rawQuery(sql, selectionArgs); return getList(cursor, ThrustData.class); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return new ArrayList<ThrustData>();
} }
package com.example.ndkreadfpga.entity;
public class ThrustData {
/** * */ public ThrustData() { // TODO Auto-generated constructor stub }
public int thrustId; public String steelNum = "1"; //轨道编号 public String fromNum = "1"; // 起点 public String toNum = "2"; // 终点 public int thrust = 3; // 受力值 public int isUnusual = 0; // 师傅异常 public long date = 16000000; // 时间
public ThrustData(String steelNum,String fromNum,String toNum,int thrust,int isUnusual,long date) { // TODO Auto-generated constructor stub this.steelNum = steelNum; this.fromNum = fromNum; this.toNum = toNum; this.thrust = thrust; this.isUnusual = isUnusual; this.date =date; }
}