1、首先写一个类继承自SQLiteOpenHelper
public class DBHelper extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION = 1; //数据库版本号
private static final String DATABASE_NAME = ""; //数据库名称
public DBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
String sql = "";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
2、需要一个数据库管理类,比如插入、删除等
public abstract class DBDao
{
private Context context;
private DBHelper dbhelper;
public SQLiteDatabase sqlitedatabase;
public DBDao(Context context)
{
super();
this.context = context;
}
/**
* 打开数据库连接
*/
public void openDB(Context context)
{
dbhelper = new DBHelper(context);
sqlitedatabase = dbhelper.getWritableDatabase();
}
/**
* 关闭数据库连接
*/
public void closeDB(Context context)
{
if (sqlitedatabase.isOpen())
{
sqlitedatabase.close();
}
}
/**
* 更新数据
*/
public int updata(String table_name, ContentValues values, int id)
{
openDB(context);
int update = sqlitedatabase.update(table_name, values, "_id=?", new String[]{String.valueOf(id)});
closeDB(context);
return update;
}
/**
* 插入数据
*/
public void insert(String table_name, ContentValues values)
{
openDB(context);
sqlitedatabase.insert(table_name, null, values);
closeDB(context);
}
/**
* 根据唯一标示_id删除数据
*/
public void delete(String table_name, int id)
{
openDB(context);
try
{
sqlitedatabase.delete(table_name, "_id=?", new String[]{String.valueOf(id)});
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
closeDB(context);
}
}
/**
* 查询数据
*/
public void search(String table_name, int id)
{
SQLiteDatabase database = dbhelper.getReadableDatabase();
String sql = "select * from " + table_name + " where _id = ?";
Cursor cursor = database.rawQuery(sql, new String[]{String.valueOf(id)});
}
}
时间: 2024-10-09 04:46:51