android orm映射框架(类似hibernate)基本使用
android orm映射框架,可像hibernate一样操作数据库。 以下代码是我从网上摘录下来的,仅供参考.
package com.cng.utils;
import java.sql.SQLException;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.cng.modal.Hello;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
public class DataHelper extends OrmLiteSqliteOpenHelper
{
private static final String DATABASE_NAME = "HelloOrmlite.db";
private static final int DATABASE_VERSION = 1;
private Dao<Hello, Integer> helloDao = null;
public DataHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource)
{
try
{
TableUtils.createTable(connectionSource, Hello.class);
} catch (SQLException e)
{
Log.e(DataHelper.class.getName(), "创建数据库失败", e);
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource,
int arg2, int arg3)
{
try
{
TableUtils.dropTable(connectionSource, Hello.class, true);
onCreate(db, connectionSource);
} catch (SQLException e)
{
Log.e(DataHelper.class.getName(), "更新数据库失败", e);
e.printStackTrace();
}
}
@Override
public void close()
{
super.close();
helloDao = null;
}
public Dao<Hello, Integer> getHelloDataDao() throws SQLException
{
if (helloDao == null)
{
helloDao = getDao(Hello.class);
}
return helloDao;
}
}
package com.cng;
import java.sql.SQLException;
import java.util.List;
import com.cng.modal.Hello;
import com.cng.utils.DataHelper;
import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import android.os.Bundle;
import android.widget.TextView;
public class OrmliteLoginActivity extends OrmLiteBaseActivity<DataHelper>
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) this.findViewById(R.id.output);
try
{
Dao<Hello, Integer> helloDao = getHelper().getHelloDataDao();
// 添加数据
for (int i = 0; i < 2; i++)
{
Hello hello = new Hello("Hello" + i);
helloDao.create(hello);
}
tv.setText(tv.getText() + "\n" + "添加数据完成");
// 查询添加的数据
List<Hello> hellos = helloDao.queryForAll();
for (Hello h : hellos)
{
tv.setText(tv.getText() + "\n" + h.toString());
}
// 删除数据第一条数据
helloDao.delete(hellos.get(0));
tv.setText(tv.getText() + "\n" + "删除数据完成");
// 重新查询数据
hellos = helloDao.queryForAll();
for (Hello h : hellos)
{
tv.setText(tv.getText() + "\n" + h.toString());
}
补充:移动开发 , Android ,