对DButils

1.首先下载xUtils

2.建立数据库单例

**
 * Created by Lampo on 16/4/22.
 */
public class DBSingle implements DbUtils.DbUpgradeListener {
    private static volatile DBSingle single;
    private final DbUtils db;

    public DBSingle(Context context) {
        db = DbUtils.create(context, Constant.CON_MICRO_CHAT.DB_NAME, Constant.CON_MICRO_CHAT.DB_VERSION, this);
       db.configDebug(DevUtils.isDebug());
       db.configAllowTransaction(true);


        try {
            createTables();
        } catch (DbException e) {
            DevUtils.d(DBSingle.class.getSimpleName(), e.getMessage());
        }
    }

    public static void init(Context context) {
        if (single != null)
            return;

        synchronized (DBSingle.class) {
            if (single == null)
                single = new DBSingle(context);
        }
    }

    public static DBSingle self() {
        if (single == null)
            throw new IllegalStateException("请初始化,调用com.mynetworktest..DBSingle.init(Context context)");
        return single;
    }

    private void createTables() throws DbException {
        db.createTableIfNotExist(User.class);
       db.createTableIfNotExist(ISession.class);
       db.createTableIfNotExist(IMessage.class);
       db.createTableIfNotExist(IQueryhistory.class);
    }

    public DbUtils DB() {
        return db;
    }

    @Override
   public void onUpgrade(DbUtils dbUtils, int i, int i1) {

    }
}


3.创建数据库表以及表参数实体类 

/**
 * Created by Lampo on 16/5/3.
 */
@Table(name = "queryhistory")//表名字
public class IQueryhistory implements Parcelable, Comparable<IQueryhistory> {
    @Id//自增
    private int id;
    @NotNull//不能为空
    private String phone;
    //查询:1 ;搜索:2;
    private int type;

    /**
     * 最后更新时间 格式标准时间描述
     */
    private long updated_at;

    public IQueryhistory() {
    }

    public IQueryhistory(Parcel in) {
        id = in.readInt();
        phone = in.readString();
        type = in.readInt();
        updated_at = in.readLong();
    }

    public static final Creator<IQueryhistory> CREATOR = new Creator<IQueryhistory>() {
        @Override
        public IQueryhistory createFromParcel(Parcel in) {
            return new IQueryhistory(in);
        }

        @Override
        public IQueryhistory[] newArray(int size) {
            return new IQueryhistory[size];
        }
    };

    @Override
    public int compareTo(IQueryhistory another) {
        if (another == null)
            return 1;
        // 为何不能直接返回-del?long数值范围多于int,逻辑上可能越界
        long del = updated_at - another.updated_at;
        if (del > 0)
            return 1;
        else if (del < 0)
            return -1;
        else
            return 0;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(phone);
        dest.writeInt(type);
        dest.writeLong(updated_at);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public long getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(long updated_at) {
        this.updated_at = updated_at;
    }
}

4.创建一个方法类 以便对数据库表数据进行修改

/**
 * 创建一条新的数据
 */
public static boolean createOrUpdate(String phone, int type) throws DbException {
    if (TextUtils.isEmpty(phone) && (type != 1 || type != 2))
        return false;
    IQueryhistory iQueryhistory = DBSingle.self().DB().findFirst(Selector.from(IQueryhistory.class).where("phone", "=", phone));
    //如果表里面没有相同的数据 新建一条数据
    if (iQueryhistory == null) {
        IQueryhistory queryhistory = new IQueryhistory();
        queryhistory.setPhone(phone);
        queryhistory.setType(type);
        queryhistory.setUpdated_at(System.currentTimeMillis());
        DBSingle.self().DB().saveBindingId(queryhistory);
        DBSingle.self().DB().saveOrUpdate(queryhistory);
    } else {
        //如果已经有相约的数据 着修改
        updateTime(iQueryhistory);
        iQueryhistory.setUpdated_at(System.currentTimeMillis());
        DBSingle.self().DB().saveOrUpdate(iQueryhistory);
    }
    return true;
}

/**
 * 删除表中所有数据(清空表)
 *
 * @throws DbException
 */
public static void deteleAll() throws DbException {
    DBSingle.self().DB().delete(IQueryhistory.class);
}

/**
 * 删除表中 类型(type)对于 1 的所有数据
 *
 * @throws DbException
 */
public static void deleteSearchhistoryAll() throws DbException {
    DBSingle.self().DB().delete(IQueryhistory.class, WhereBuilder.b("type", "=", 2));
}

/**
 * 修改单一参数
 *
 * @param iQueryhistory
 * @throws DbException
 */
public static void updateTime(IQueryhistory iQueryhistory) throws DbException {
    DBSingle.self().DB().update(iQueryhistory, "updated_at");
}

/**
 * 修改多个参数
 *
 * @param iQueryhistory
 * @throws DbException
 */
public static void updateTimeAndType(IQueryhistory iQueryhistory) throws DbException {
    DBSingle.self().DB().update(iQueryhistory, "updated_at", "type");
}

/**
 * 获取表中所有数据
 *
 * @return
 * @throws DbException
 */
public static List<IQueryhistory> getList() throws DbException {
    return DBSingle.self().DB().findAll(IQueryhistory.class);
}

/**
 * 获取表中所有数据 并按时间(updated_at)排序
 * true 正序
 *
 * @return list
 * @throws DbException
 */
public static List<IQueryhistory> getListOrderBy() throws DbException {
    return DBSingle.self().DB().findAll(Selector.from(IQueryhistory.class).orderBy("updated_at", true));
}

/**
 * 获取表中所有 类型(type)等于 1 的数据 并按时间(updated_at)排序
 * true 正序
 *
 * @return list
 * @throws DbException
 */
public static List<IQueryhistory> getQueryhistoryList() throws DbException {
    return DBSingle.self().DB().findAll(Selector.from(IQueryhistory.class).where("type", "=", 1).orderBy("updated_at", true));
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python DBUtils 是一个轻量级的 Python 数据库连接池库,支持多个线程和多个进程,并可与各种数据库后端一起使用。DBUtils 是一个纯 Python 库,没有其他依赖项。 DBUtils 的主要目的是提供一个共享数据库连接池,这样可以避免在不同的线程和进程中频繁地打开和关闭数据库连接。这可以极大地提高应用程序的性能和响应速度。 DBUtils 提供了一些常见的数据库连接池实现,包括 PooledDB,PersistentDB 和 StackedObjectPool。这些实现都提供了相同的接口,因此可以很容易地将它们用于不同的应用程序。 使用 DBUtils 可以在保持代码简洁的同时获得数据库连接池的好处。以下是一个使用 DBUtils 连接 MySQL 数据库的示例: ```python import pymysql from dbutils.pooled_db import PooledDB POOL = PooledDB( creator=pymysql, maxconnections=5, mincached=2, maxcached=5, blocking=True, maxusage=None, host='localhost', port=3306, user='root', password='password', database='test', charset='utf8mb4' ) def get_conn(): return POOL.connection() def query_data(sql): conn = get_conn() cursor = conn.cursor() cursor.execute(sql) result = cursor.fetchall() cursor.close() conn.close() return result ``` 在上面的示例中,我们使用 `PooledDB` 创建了一个 MySQL 数据库连接池,并使用 `get_conn` 获取一个连接对象,然后使用 `query_data` 函数执行 SQL 查询。注意,我们在使用完连接后需要手动关闭连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值