<dependency> <groupId>com.j256.ormlite</groupId> <artifactId>ormlite-core</artifactId> <version>5.6</version> </dependency> @DatabaseTable(tableName = "students") public class Student { @DatabaseField(generatedId = true) private int id; @DatabaseField private String name; } public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final String DATABASE_NAME = "mydatabase.db"; private static final int DATABASE_VERSION = 1; private Dao<Student, Integer> studentDao; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { TableUtils.createTable(connectionSource, Student.class); } catch (SQLException e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) { try { TableUtils.dropTable(connectionSource, Student.class, true); onCreate(database, connectionSource); } catch (SQLException e) { e.printStackTrace(); } } public Dao<Student, Integer> getStudentDao() throws SQLException { if (studentDao == null) { studentDao = getDao(Student.class); } return studentDao; } } DatabaseHelper databaseHelper = new DatabaseHelper(context); Dao<Student, Integer> studentDao = databaseHelper.getStudentDao(); Student student = new Student(); studentDao.create(student); List<Student> students = studentDao.queryForAll(); QueryBuilder<Student, Integer> queryBuilder = studentDao.queryBuilder(); List<Student> matchingStudents = queryBuilder.query(); studentDao.update(student); studentDao.delete(student); databaseHelper.close();


上一篇:
下一篇:
切换中文