package com.edu.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBUtil extends SQLiteOpenHelper {
public DBUtil(Context context) {
/**
* 1.数据创建位置
* 2.数据库文件名
* 3.游标,null 默认方式
* 4.版本号
*/
super(context, "edu.db", null, 1);
}
/**
* 获取SQLiteDateBase对象的时候,自动执行
* @param db
*/
@Override
public void onCreate(SQLiteDatabase db) {
//建表
String sql = "create table stu_info"
+ "("
+ "stu_id integer PRIMARY KEY"
+ "stu_name text,"
+ "stu_age text"
+ ")";
db.execSQL(sql);
System.out.println("END");
}
/**
* 版本号变更,自动执行
* 先删除,然后创建
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//删除表
String sql = "drop table if exists stu_info";
db.execSQL(sql);
onCreate(db);
}
}
DBUtil util = new DBUtil(this, rp);
SQLiteDatabase db = util.getWritableDatabase();
//Object[] params = {};
String sql1 = "insert into user_info(user_id,user_name) "
+ "values(1,'张三')";
String sql2 = "delete from user_info where user_id = ? ";
String sql3 = "update user_info set user_name=?,password=?,sex=?"
+ " where user_id = ? ";
db.execSQL(sql);
//db.execSQL(sql2, params);
//db.execSQL(sql3, params);
select
List> list = new ArrayList<>();
HashMap
db.insert(table, nullColumnHack, values);
db.delete(table, whereClause, whereArgs);
db.update(table, values, whereClause, whereArgs);
db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
ContentValues cv = new ContentValues();
cv.put("username", "zhangsan");
database_name=work.db
version=1
table_create=create table user_info\
(\
user_id integer PRIMARY KEY,\
user_name text,\
password text,\
sex text\
)
创建一个工具类,继承SQLiteOpenHelper抽象类,重写OnCreate和OnUpgrade方法,获取资源文件中的SQL建表语句。
package com.edu.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* 数据库操作帮助类
* @author xukai
* 2015年11月28日
*
*/
public class DBUtil extends SQLiteOpenHelper {
private ReadProperties rp;
/**
* @param context 上下文
* @param rp properties文件
*/
public DBUtil(Context context, ReadProperties rp) {
super(context, rp.getDataBaseName(), null, rp.getDataBaseVersion());
this.rp = rp;
}
/**
* 创建表语句,SQLiteDatabase.getReadableDatabase() or
* getWriteableDatabase时执行
*/
@Override
public void onCreate(SQLiteDatabase db) {
String[] array = rp.getCreateSQL();
for(String str : array){
db.execSQL(str);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
}
}
package com.edu.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.edu.util.DBUtil;
import com.edu.util.ReadProperties;
public class BaseDao {
private DBUtil dbUtil;
private ReadProperties rp;
private SQLiteDatabase db;
public BaseDao(Context context) {
rp = new ReadProperties(context);
dbUtil = new DBUtil(context, rp);
}
/**
* 执行insert delete update操作
* @param sql SQL语句
* @param objects 值
*/
protected void executeUpdate(String sql, Object...objects){
try {
db = dbUtil.getWritableDatabase();
/**
* 判断参数是否为空
*/
if(objects != null && objects.length > 0){
db.execSQL(sql, objects);
}else{
db.execSQL(sql);
}
} catch (SQLException e) {
throw new RuntimeException("exception:BaseDao.executeUpdate()", e);
} finally{
if(db != null && db.isOpen()){
db.close();
}
}
}
/**
* 执行查询操作
* @param sql SQL语句
* @param objects 条件
* @return List> 结果集
*/
protected List> executeQuery(String sql, Object[] objects){
List> list = new ArrayList<>();
HashMap
package com.edu.dao.impl;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import com.edu.dao.BaseDao;
/**
* 数据库操作实现类
* @author xukai
* 2015年11月28日
*
*/
public class UserInfoDaoImpl extends BaseDao {
public UserInfoDaoImpl(Context context) {
super(context);
}
/**
* 添加
*/
public void save(Object[] objects){
String sql = "insert into user_info(user_name, password, sex)"
+ " values(?, ?, ?)";
super.executeUpdate(sql, objects);
}
/**
* 删除
*/
public void delete(Object[] objects){
String sql = "delete from user_info where user_id = ? ";
super.executeUpdate(sql, objects);
}
/**
* 更改
*/
public void update(Object[] objects){
String sql = "update user_info set user_name=?,password=?,sex=?"
+ " where user_id = ? ";
super.executeUpdate(sql, objects);
}
/**
* 查询所有
*/
public List> find(){
String sql = "select * from user_info ";
return super.executeQuery(sql, null);
}
}
package com.edu.pro1125_sqlite_work.test;
import org.junit.Before;
import org.junit.Test;
import android.test.AndroidTestCase;
import com.edu.dao.impl.UserInfoDaoImpl;
public class TestUserInfoImpl extends AndroidTestCase {
private UserInfoDaoImpl dao;
@Before
protected void setUp() throws Exception {
super.setUp();
dao = new UserInfoDaoImpl(getContext());
}
@Test
public void test() {
dao.save(new Object[]{"测试用户1","111","男"});//其他方法测试相同
}
}
右键,run as->JUnit Test Case,测试通过,在模拟器File Explorer中data/data/package_name/databases/database_name.db,导出该文件,可以通过Navicat查看数据。
package com.edu.contentprovider;
import com.edu.util.DBUtil;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
public class MyContentProvider extends ContentProvider {
private DBUtil dbutil;
private SQLiteDatabase db;
//常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
/**
* 添加Uri,如果匹配,返回匹配码
*/
static{
matcher.addURI("com.edu.contentprovider", "user_info", 1);
matcher.addURI("com.edu.contentprovider", "book_info", 2);
}
@Override
public boolean onCreate() {
dbutil = new DBUtil(getContext());
return false;
}
/**
*
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
String table = "";
//匹配Uri,返回对应码
switch (matcher.match(uri)) {
case 1:
table = "user_info";
break;
case 2:
table = "book_info";
}
db = dbutil.getReadableDatabase();
return db.query(table, projection, selection, selectionArgs, null, null, sortOrder);
}
//返回数据的格式
@Override
public String getType(Uri uri) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
String table = "";//根据对应Uri,判断操作的表
switch (matcher.match(uri)) {
case 1:
table = "user_info";
break;
case 2:
table = "book_info";
}
db = dbutil.getWritableDatabase();
db.insert(table, null, values);
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
db = dbutil.getWritableDatabase();
return db.delete("user_info", selection, selectionArgs);
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
db = dbutil.getWritableDatabase();
return db.update("user_info", values, selection, selectionArgs);
}
}
AndroidManifest.xml:
Project2:
对Project1中的表进行操作 ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
// values.put("user_name", "马莎莎");
// values.put("user_pwd", "123456");
values.put("book_name", "Java程序设计");
values.put("book_price", "80.0");
values.put("book_num", "10");
//格式 contend://provider_name -> android:authorities
Uri uri = Uri.parse("content://com.edu.contentprovider/book_info");
cr.insert(uri, values);
导出数据库文件: