Sqlite的使用和一个简单的书籍管理系统(上)

虽然说app与网络打交道比较多但是本地存储数据库sqlite还是有它很重要的责任

那来一起学习一下sqlite吧
android的存储方式有如下几种
http://blog.csdn.net/a351945755/article/details/50900652
等我有时间就整理下

sharedpreferences
文件存储
sqlite数据库
contentprovider
网络

我们来看看sqlite
他通过SQLiteOpenHelper这个抽象类;来创建和打开数据库

public class DBHelper extends SQLiteOpenHelper {
    private static final String DATA_NAME = "jaytang.db";
    private static final int version = 1;// 版本
    private static final String TAG = "DBHelper";// 版本

    public DBHelper(Context context) {
        super(context, DATA_NAME, null, version);
        // TODO Auto-generated constructor stub
    }

    /**
     * 数据库第一次创建时回调该方法,一般做数据库的初始化操作 建表,添加数据等 SQLiteDatabase:增删查改
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        Log.v(TAG, "创建表");
        db.execSQL("create table t_book(_id integer primary key autoincrement,name text,price integer)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

}

重写一个DBhelper来继承SQLiteOpenHelper
并重写他里面的方法;在oncreate方法里面新建一个表

    db.execSQL("create table t_book(_id integer primary key autoincrement,name text,price integer)");

这样我们就新建了一个表了
可以在 project Explorer里面查看我们新建的数据库jaytang.db
再来写一个工具类来实现数据库的增删查改方法
通过数据库的辅助类SQLiteDatabase来操作

/**
 * 操作数据库的工具类
 * 
 * @author Jay-Tang
 * 
 */
public class DButils {
    public static final String TABLE = "t_book";
    public static final String ID = "id";
    public static final String NAME = "name";
    public static final String PRICE = "price";
    private DBHelper dbhelper;

    public DButils(Context context) {
        dbhelper = new DBHelper(context);

    }

    // 保存操作
    public int save(ContentValues values) {
        // 通过数据库的辅助类来获取SQliteDatabase
        // 没有设置成全局因为每个操作都要用
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        /**
         * 插入一条记录 表名 空字段回调:目的在于拼sql语句时不报错 第三个参数是键值对 插入字段的key和value
         */
        long id = db.insert(TABLE, null, values);
        db.close();
        return (int) id;
    }

    // 删除操作
    public int delete(int id) {
        int effectNum = 0;
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        /**
         * 删除操作 表 条件 条件操作 源码是拼串构成的
         */
        effectNum = db.delete(TABLE, ID + "=?",
                new String[] { String.valueOf(id) });
        db.close();
        return effectNum;
    }

    // 更新要求ContentValues传一个id过来
    public int update(ContentValues values) {
        // 更新那个位置就传那个位置的id过来
        String id = values.getAsString(ID);
        // 影响的行数
        int effecNums = 0;
        SQLiteDatabase db = dbhelper.getWritableDatabase();
        effecNums = db.update(TABLE, values, ID + "=" + id, null);
        db.close();
        return effecNums;
    }

    // 查询
    public Cursor findcursor() {
        SQLiteDatabase db = dbhelper.getReadableDatabase();
        Cursor cursor = db.query(TABLE, null, null, null, null, null, null,
                "price disc");
        return cursor;
        // 假如是返回游标不嫩关闭数据库
    }

    // 查询,返回的是list<map>
    public List<Map<String, Object>> find() {
        List<Map<String, Object>> data = null;
        SQLiteDatabase db = dbhelper.getReadableDatabase();
        Cursor cursor = db.query(TABLE, null, null, null, null, null, null,
                "price disc");
        // 假如有数据
        if (cursor.getCount() > 0) {
            data = new ArrayList<Map<String, Object>>();
        }
        // 遍历游标,把数据存放在list中
        while (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put(ID, cursor.getInt(cursor.getColumnIndex(ID)));
            map.put(NAME, cursor.getInt(cursor.getColumnIndex(NAME)));
            map.put(PRICE, cursor.getInt(cursor.getColumnIndex(PRICE)));
            data.add(map);
        }
        db.close();
        return data;
    }

    public void pay() {

    }

}

上面的工具类DButils能基本实现增删改查的效果
//工具类是可以复用的 所以尽量写好,并且进行单元测试

布局文件如下

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        android:text="书籍管理系统"
        android:textColor="#0000ff"
        android:textSize="22sp" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <TextView
            style="@style/MyTitleStyle"
            android:text="编号" />

        <TextView
            style="@style/MyTitleStyle"
            android:layout_weight="2"
            android:text="书名" />

        <TextView
            style="@style/MyTitleStyle"
            android:text="价格" />

        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@drawable/ic_menu_delete"
            android:visibility="invisible" />
    </LinearLayout>

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:divider="#0000ff"
        android:dividerHeight="2dp" >
    </ListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <EditText
            android:id="@+id/name_et"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="书名" />

        <EditText
            android:id="@+id/price_et"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="价格"
            android:inputType="number" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="add"
            android:text="添加" />
    </LinearLayout>

</LinearLayout>

效果图

转载于:https://www.cnblogs.com/Tesi1a/p/7624151.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个简单的示例,演示如何使用 FastAPI 和 SQLite 创建一个档案库管理系统。 首先,安装必要的库: ``` pip install fastapi pip install uvicorn pip install databases pip install sqlalchemy ``` 然后,创建一个 `main.py` 文件,并输入以下代码: ```python from fastapi import FastAPI from pydantic import BaseModel from typing import List import databases from databases import Database import sqlalchemy from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String app = FastAPI() # 数据库配置信息 DATABASE_URL = "sqlite:///./test.db" # 创建数据库连接 database = Database(DATABASE_URL) # SQLAlchemy 元数据 metadata = MetaData() # 模型对应的数据库表 books = Table( "books", metadata, Column("id", Integer, primary_key=True), Column("title", String(50)), Column("author", String(50)), Column("description", String(200)), Column("price", Integer), ) # 创建数据库表 engine = create_engine(DATABASE_URL) metadata.create_all(engine) # 数据模型 class Book(BaseModel): title: str author: str description: str price: int # 创建新书籍 @app.post("/books/") async def create_book(book: Book): query = books.insert().values( title=book.title, author=book.author, description=book.description, price=book.price, ) last_record_id = await database.execute(query) return {**book.dict(), "id": last_record_id} # 获取所有书籍 @app.get("/books/") async def read_books(): query = books.select() results = await database.fetch_all(query) return results # 获取单个书籍 @app.get("/books/{book_id}") async def read_book(book_id: int): query = books.select().where(books.c.id == book_id) result = await database.fetch_one(query) if result: return result else: return {"error": "Book not found"} # 更新书籍 @app.put("/books/{book_id}") async def update_book(book_id: int, book: Book): query = ( books.update() .where(books.c.id == book_id) .values( title=book.title, author=book.author, description=book.description, price=book.price, ) ) await database.execute(query) return {**book.dict(), "id": book_id} # 删除书籍 @app.delete("/books/{book_id}") async def delete_book(book_id: int): query = books.delete().where(books.c.id == book_id) await database.execute(query) return {"message": "Book deleted successfully"} # 连接到数据库 @app.on_event("startup") async def startup(): await database.connect() # 断开数据库连接 @app.on_event("shutdown") async def shutdown(): await database.disconnect() ``` 这个示例创建了一个名为 `books` 的数据库表,用于存储书籍信息。它提供了以下 API: - `POST /books/`:创建新书籍 - `GET /books/`:获取所有书籍 - `GET /books/{book_id}`:获取单个书籍 - `PUT /books/{book_id}`:更新书籍 - `DELETE /books/{book_id}`:删除书籍 你可以使用 SQLite 数据库浏览器等工具来管理数据。 最后,在命令行中运行以下命令启动应用程序: ``` uvicorn main:app --reload ``` 现在,你可以通过浏览器或其他 HTTP 客户端来访问这些 API。例如,要创建一个书籍: ``` POST http://localhost:8000/books/ { "title": "Python入门教程", "author": "张三", "description": "一本Python入门教程", "price": 50 } ``` 要获取所有书籍: ``` GET http://localhost:8000/books/ ``` 要获取单个书籍: ``` GET http://localhost:8000/books/1 ``` 要更新书籍: ``` PUT http://localhost:8000/books/1 { "title": "Python入门教程2", "author": "张三", "description": "一本Python入门教程", "price": 60 } ``` 要删除书籍: ``` DELETE http://localhost:8000/books/1 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值