thinkAndroid数据库框架
下载jar包放入libs中
新建MyApplication继承TAApplication
public class MyApplication extends TAApplication {
@Override
public void onCreate() {
super.onCreate();
}
}
AndroidManifest中注册MyApplication
<application
......
android:name=".MyApplication">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
创建保存用户信息的实体类UserEntity
public class UserEntity implements Serializable {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
创建一个DAO
public class UserDAO {
public UserDAO(TAApplication taApplication) {
//创建表
TASQLiteDatabasePool pool = taApplication.getSQLiteDatabasePool();
//从池中取对象
TASQLiteDatabase database = pool.getSQLiteDatabase();
//没有表
//通过反射得到类的包名、类名、属性名
if (!database.hasTable(UserEntity.class)) {
database.creatTable(UserEntity.class);
}
//对象用完要放回池
pool.releaseSQLiteDatabase(database);
}
public void insert(TAApplication taApplication, UserEntity userEntity) {
TASQLiteDatabasePool pool = taApplication.getSQLiteDatabasePool();
TASQLiteDatabase database = pool.getSQLiteDatabase();
//利用反射得到对象属性名
database.insert(userEntity);
pool.releaseSQLiteDatabase(database);
}
public List<UserEntity> queryAll(TAApplication taApplication) {
TASQLiteDatabasePool pool = taApplication.getSQLiteDatabasePool();
TASQLiteDatabase database = pool.getSQLiteDatabase();
//第一个参数:从哪读
//第二个参数:有相同行,取一个
//第三个参数:where
//第四个参数:groupby
List<UserEntity> list = database.query(UserEntity.class, true, null, null, null, null, null);
pool.releaseSQLiteDatabase(database);
return list;
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyApplication application = (MyApplication) getApplication();
UserEntity entity1 = new UserEntity();
entity1.setUsername("周杰伦");
entity1.setPassword("zhoujielun");
UserDAO userDAO = new UserDAO(application);
userDAO.insert(application,entity1);
UserEntity entity2 = new UserEntity();
entity2.setUsername("许嵩");
entity2.setPassword("xusong");
userDAO.insert(application,entity2);
ArrayList<UserEntity> list = new ArrayList(userDAO.queryAll(application));
Log.d("test","数量:"+list.size());
}
}
运行程序可以查看到日志输出的数量为2
我们查看data/data目录
可以看到目录包名下创建了一个数据库think_android.db
我们用命令查看这个数据库
关于命令行的操作可以查看
【SQLite数据库存储】创建、升级数据库
也可以下载下来使用SQLite Expert Professional查看